using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Xml;
using System.Data.SqlClient;
using System.Text;
using System.Drawing.Printing;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
//using C1.C1Report;
//using C1.Web.C1WebReport;
using AjaxControlToolkit;
using MBLocale;

public partial class ReportWizard : System.Web.UI.Page
{
    DataTable dtObj = null;
    HDDatabase hdd = null;
    security hdds = null;
    ScreenReader SR = null;
    DataSet dsPageInfo = null;
    DataSet dsReport = new DataSet();
    DataSet dsRptSrcFlt = null; // Added by Imran Gani on 20-Jul-2012, for Source Filter.
    HtmlTable htProperties;
    string m_PageSetId = "6421de320e189de8"; // ps_report
    bool IsEdit = false;
    string m_PageKey = "";
    string m_Report_id = "";
    List<Stream> m_streams;
    System.Windows.Forms.PrintDialog printDialog1 = new System.Windows.Forms.PrintDialog();
    int m_currentPageIndex = 0;
    string exportType = "";

    protected void Page_PreInit(object sender, EventArgs e)
    {
        this.Theme = Session["Theme"].ToString();
        this.Title = "MaxBlox";
        hdd = new HDDatabase();
        hdds = new security();
        SR = new ScreenReader();
    }

    protected void Page_UnLoad(object sender, EventArgs e)
    {
        //Session["report_ds"] = null;
    }

    private bool getExportValue()
    {
        bool ret = false;
        HDDatabase hd = new HDDatabase();
        try
        {
            DataTable dt = hd.GetDataTable("select * from sy_acr_mem where af_row_id='" + "76cf74c043053300" + "'");
            if (dt != null)
            {
                if (dt.Rows.Count > 0)
                {
                    ret = dt.Rows[0]["mem_value1"].ToString().ToLower() == "true";
                }
            }
        }
        catch (Exception e)
        {
            LogWriter.WriteLog("Error in getExportValue: " + e.Message);
        }
        finally
        {
            hd = null;
        }
        return ret;
    }

    private void makeControlsVisible(bool fg)
    {
        try
        {
            DynamicDisplayI ddI = new DynamicDisplayI();
            ImageButton btn = (ImageButton)ddI.FindControl(Master.FindControl("ContentPlaceHolder3").FindControl("wz_report").FindControl("StartNavigationTemplateContainerID").Controls, "btnExport");
            if (btn != null)
                btn.Visible = fg;
            btn = null;

            btn = (ImageButton)ddI.FindControl(Master.FindControl("ContentPlaceHolder3").FindControl("wz_report").FindControl("StartNavigationTemplateContainerID").Controls, "btnExport_menu");
            if (btn != null)
                btn.Visible = fg;
            btn = null;

            //Start Navigation
            Menu mnu = (Menu)ddI.FindControl(Master.FindControl("ContentPlaceHolder3").FindControl("wz_report").FindControl("StartNavigationTemplateContainerID").Controls, "mnuExportoptions");
            if (mnu != null)
                mnu.Visible = fg;
            mnu = null;

            mnu = (Menu)ddI.FindControl(Master.FindControl("ContentPlaceHolder3").FindControl("wz_report").FindControl("StartNavigationTemplateContainerID").Controls, "mnuOptions");
            if (mnu != null)
            {
                foreach (MenuItem mi in mnu.Items)
                {
                    if (mi.Text.ToLower().EndsWith("export"))
                    {
                        mi.Enabled = fg;
                        break;
                    }
                }
            }
            mnu = null;

            //Step Navigation
            btn = (ImageButton)ddI.FindControl(Master.FindControl("ContentPlaceHolder3").FindControl("wz_report").FindControl("StepNavigationTemplateContainerID").Controls, "btnExport");
            if (btn != null)
                btn.Visible = fg;
            btn = null;

            btn = (ImageButton)ddI.FindControl(Master.FindControl("ContentPlaceHolder3").FindControl("wz_report").FindControl("StepNavigationTemplateContainerID").Controls, "btnExport_menu");
            if (btn != null)
                btn.Visible = fg;
            btn = null;

            //Start Navigation
            mnu = (Menu)ddI.FindControl(Master.FindControl("ContentPlaceHolder3").FindControl("wz_report").FindControl("StepNavigationTemplateContainerID").Controls, "mnuExportoptions");
            if (mnu != null)
                mnu.Visible = fg;
            mnu = null;

            mnu = (Menu)ddI.FindControl(Master.FindControl("ContentPlaceHolder3").FindControl("wz_report").FindControl("StepNavigationTemplateContainerID").Controls, "mnu_Options_step2");
            if (mnu != null)
            {
                foreach (MenuItem mi in mnu.Items)
                {
                    if (mi.Text.ToLower().EndsWith("export"))
                    {
                        mi.Enabled = fg;
                        break;
                    }
                }
            }
            mnu = null;



            ddI = null;
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("makeControlsVisible: Error: " + ex.Message);
        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            if (Session["userid"] == null || Session["userid"].ToString() == "") 
                Response.Redirect(hdds.SessionExpiryURL);//karthik to check session expiry
            imgNewWindow.Visible = false;
            if (Request.QueryString["mn"] != null)
                hdds.logMenuClick(Request.QueryString["mn"].ToString());

            if (Session["userid"] == null) Response.Redirect(hdds.SessionExpiryURL);
            if (Session["userid"].ToString() == "") Response.Redirect(hdds.SessionExpiryURL);

            // Below code commented by 'Imran Gani' on 27-Jun-2013, since the reports have listed based on owner and access rights, we can render the report-data without checking object
            //Code added by Sampath on 15-Nov-2011 for IPP Vertical privilege
            //if (Request.QueryString["PK"] != null && Request.QueryString["pgs_id"] != null)
            //{
            //    if (!hdds.checkRecordAccess(Request.QueryString["PK"].ToString(), Request.QueryString["pgs_id"].ToString()))
            //    {
            //        lblerrmsg.Text = wrapItAsMessage("<img src=\"Images/info.gif\" alt=\"\"></img>&nbsp;You do not have sufficient access permission.", true);
            //        wz_Report.Visible = false;
            //        return;
            //    }
            //}

            //Code added by Sampath on 18-Nov-2011 for IPP Vertical privilege
            if (Request.QueryString["mn"] != null)
            {
                if (!hdds.checkObjectMenuAccess(Request.QueryString["mn"]))
                {
                    wz_Report.Visible = false;
                    lblerrmsg.Text = wrapItAsMessage("<img src=\"Images/info.gif\" alt=\"\"></img>&nbsp;You do not have sufficient access permission.", true);
                    return;
                }
            }

            if (!IsPostBack)
            {
                Session["report_ds"] = null;
                Session["FieldProperties"] = null;
                Session["param"] = null;
                Session["showReport"] = null;
            }

            wz_Report.DisplaySideBar = false;
            
            IsActionMode(); // Added by srivatsan for action 

            #region loading Dataset
            if (dsPageInfo == null)
            {
                PageInfoLoad objPIL = new PageInfoLoad();
                dsPageInfo = objPIL.GetPageSetPageCtrlInfo(m_PageSetId);
                DataSet dsPageInfo1 = objPIL.GetPageSetPageCtrlInfo("1115c5d9f03853ab"); // ps_report_obj
                DataSet dsPageInfo2 = objPIL.GetPageSetPageCtrlInfo("6e0a8813dec48f1f"); // ps_report_att
                dsPageInfo.Tables["Page"].Merge(dsPageInfo1.Tables["Page"]);
                dsPageInfo.Tables["Page"].Merge(dsPageInfo2.Tables["Page"]);
                dsPageInfo.Tables["PageCtrl"].Merge(dsPageInfo1.Tables["PageCtrl"]);
                dsPageInfo.Tables["PageCtrl"].Merge(dsPageInfo2.Tables["PageCtrl"]);
                dsPageInfo.Tables["PageKeys"].Merge(dsPageInfo1.Tables["PageKeys"]);
                dsPageInfo.Tables["PageKeys"].Merge(dsPageInfo2.Tables["PageKeys"]);
                dsPageInfo1 = null;
                dsPageInfo2 = null;
                //new tables
                //source filter // Added by 'Imran Gani' on 30-May-2012
                dsPageInfo1 = objPIL.GetPageSetPageCtrlInfo("f5615b2f5f6aa17e"); // report_source_filter
                dsPageInfo.Tables["Page"].Merge(dsPageInfo1.Tables["Page"]);
                dsPageInfo.Tables["PageCtrl"].Merge(dsPageInfo1.Tables["PageCtrl"]);
                dsPageInfo.Tables["PageKeys"].Merge(dsPageInfo1.Tables["PageKeys"]);
                dsPageInfo1 = null;
                //header footer
                dsPageInfo1 = objPIL.GetPageSetPageCtrlInfo("4464f43fb5ec15e9"); // ps_report_header_footer
                dsPageInfo.Tables["Page"].Merge(dsPageInfo1.Tables["Page"]);
                dsPageInfo.Tables["PageCtrl"].Merge(dsPageInfo1.Tables["PageCtrl"]);
                dsPageInfo.Tables["PageKeys"].Merge(dsPageInfo1.Tables["PageKeys"]);
                dsPageInfo1 = null;
                //grouping
                dsPageInfo1 = objPIL.GetPageSetPageCtrlInfo("4029ae463fc3effa"); // report_grouping
                dsPageInfo.Tables["Page"].Merge(dsPageInfo1.Tables["Page"]);
                dsPageInfo.Tables["PageCtrl"].Merge(dsPageInfo1.Tables["PageCtrl"]);
                dsPageInfo.Tables["PageKeys"].Merge(dsPageInfo1.Tables["PageKeys"]);
                dsPageInfo1 = null;
                //report_grouping_header
                dsPageInfo1 = objPIL.GetPageSetPageCtrlInfo("30567670e00d3740"); // report_grouping_header
                dsPageInfo.Tables["Page"].Merge(dsPageInfo1.Tables["Page"]);
                dsPageInfo.Tables["PageCtrl"].Merge(dsPageInfo1.Tables["PageCtrl"]);
                dsPageInfo.Tables["PageKeys"].Merge(dsPageInfo1.Tables["PageKeys"]);
                dsPageInfo1 = null;
                //report_grouping_subtotal
                dsPageInfo1 = objPIL.GetPageSetPageCtrlInfo("292898b0d2a017b0"); // report_grouping_subtotal
                dsPageInfo.Tables["Page"].Merge(dsPageInfo1.Tables["Page"]);
                dsPageInfo.Tables["PageCtrl"].Merge(dsPageInfo1.Tables["PageCtrl"]);
                dsPageInfo.Tables["PageKeys"].Merge(dsPageInfo1.Tables["PageKeys"]);
                dsPageInfo1 = null;
                #region commented for Phase 1
                ////report_grouping_sort_details
                //dsPageInfo1 = objPIL.GetPageSetPageCtrlInfo("report_grouping_sort_details");
                //dsPageInfo.Tables["Page"].Merge(dsPageInfo1.Tables["Page"]);
                //dsPageInfo.Tables["PageCtrl"].Merge(dsPageInfo1.Tables["PageCtrl"]);
                //dsPageInfo.Tables["PageKeys"].Merge(dsPageInfo1.Tables["PageKeys"]);
                //dsPageInfo1 = null;
                #endregion
                //report_grouping_grand_total
                dsPageInfo1 = objPIL.GetPageSetPageCtrlInfo("a3ed5f958dbc7ecc"); // report_grouping_grand_total
                dsPageInfo.Tables["Page"].Merge(dsPageInfo1.Tables["Page"]);
                dsPageInfo.Tables["PageCtrl"].Merge(dsPageInfo1.Tables["PageCtrl"]);
                dsPageInfo.Tables["PageKeys"].Merge(dsPageInfo1.Tables["PageKeys"]);
                dsPageInfo1 = null;
            }
            #endregion

            if (Request.QueryString["PK"] != null)
            {
                m_PageKey = Request.QueryString["PK"].ToString();
                if (!IsPostBack)
                    hf_af_row_id1.Value = m_PageKey;
                m_Report_id = hdd.GetColumnValue("select rpt_id from sy_report where af_row_id = '" + m_PageKey + "'");
                if (Request.QueryString["CPY"] != null)
                {
                    if (Request.QueryString["CPY"] == "0")
                    {
                        wz_Report.HeaderText = "Report Wizard - Copy";
                        Label lbl = (Label)this.Master.FindControl("ContentPlaceHolder3").FindControl("wz_report").FindControl("HeaderContainer").FindControl("Label3");
                        if (lbl != null) lbl.Text = "Report Wizard - Copy";
                        IsEdit = false;
                    }
                    else
                    {
                        wz_Report.HeaderText = "Report Wizard - Edit";
                        Label lbl = (Label)this.Master.FindControl("ContentPlaceHolder3").FindControl("wz_report").FindControl("HeaderContainer").FindControl("Label3");
                        if (lbl != null) lbl.Text = "Report Wizard - Edit";
                        IsEdit = true;
                    }
                }
                else
                {
                    wz_Report.HeaderText = "Report Wizard - Edit";
                    Label lbl = (Label)this.Master.FindControl("ContentPlaceHolder3").FindControl("wz_report").FindControl("HeaderContainer").FindControl("Label3");
                    if (lbl != null) lbl.Text = "Report Wizard - Edit";
                    IsEdit = true;
                }
            }

            if (!IsPostBack)
            {
                MyRDLC myrdlc = new MyRDLC();
                string sBG0 = myrdlc.getCSSPropertyValue(".Grid_Report_Header", "background-color");
                if (sBG0 == "") sBG0 = "#FFFFFF";
                reportViewer.BackColor = System.Drawing.ColorTranslator.FromHtml(sBG0);
                reportViewer.BorderStyle = BorderStyle.None;
                
                getpageicons();
                loadOwneridDropDown();//Added by srivatsan
            }

            CheckForChangeOwner();

            string strPK = "";
            if (Request.QueryString["PK"] != null)
            {
                strPK = Request.QueryString["PK"].ToString();
            }
            imgsearch.Attributes.Add("onclick", "javascript:openlookupwindow('wz_Report_owner_id','wz_Report_txt_owner_id','f496930dfe0b690f','" + strPK + "','" + Request.QueryString["pgs_id"].ToString() + "');");

            if (IsEdit)
            {
                if (Session["report_ds"] != null)
                    dsReport = (DataSet)Session["report_ds"];
            }
            else
                if (!IsPostBack)
                    hf_af_row_id1.Value = SR.getHashKey();

            if (!IsPostBack)
            {
                string sSql = "Select * from sy_obj order by object_name asc";
                loadObjectsinCombo(sSql);
            }
            else
            {
                if (lstSelectedFields1.Items.Count > 0)
                    showFieldProperties();
            }

            if (cmbObjects.SelectedIndex != -1)
            {
                lblMsgStep2.Text = cmbObjects.SelectedItem.Text + "$" + cmbObjects.SelectedValue.Substring(cmbObjects.SelectedValue.IndexOf("@")+1);
                if (hiddenGroupCnt.Value.Trim() == "") hiddenGroupCnt.Value = "1";
            }

            if (Session["report_ds"] != null)
                dsReport = (DataSet)Session["report_ds"];
            
            for (int i = 1; i <= Convert.ToInt32(hiddenGroupCnt.Value); i++)
                createGroupingForm(i);

            checkEditCopyOperation();
            isViewMode();

            if (dsRptSrcFlt == null && wz_Report.ActiveStepIndex > 0) // Added by Imran Gani on 20-Jul-2012, for Source Filter.
                FillSourceFilterFields(); 

            if (hiddenParam.Value == "P")//&& wz_Report.ActiveStepIndex > 3
                createParameters();

            bool IsExport = getExportValue();
            if (IsExport)
            {
                lblExport.Visible = true;
                ddlExport.Visible = true;
                lnkExport.Visible = true;

                makeControlsVisible(true);
            }
            else
            {
                lblExport.Visible = false;
                ddlExport.Visible = false;
                lnkExport.Visible = false;

                makeControlsVisible(false);
            }

            if (IsPostBack)
                return;
            //reportViewer.Report.Tag = DateTime.Now.ToString();//for refreshing report
            if (HttpContext.Current.Request.QueryString["VMODE"] != null)//Added during reporting control change
                if (HttpContext.Current.Request.QueryString["VMODE"] == "1")//Added during reporting control change
                    generateReport(false, "");

            //if (!IsPostBack)
            //{
            //    reportViewer_CurrentPageChanged(this, EventArgs.Empty);
            //}
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("PageLoad : Error : " + ex.Message);
        }
    }

    private void createParameters()
    {
        //if (wz_Report.ActiveStepIndex < 4) return;
        try
        {
            DynamicDisplayI ddI = new DynamicDisplayI();
            HtmlTable tblParm = (HtmlTable)ddI.FindControl(Master.FindControl("ContentPlaceHolder3").FindControl("wz_report").Controls, "tblParam");
            if (tblParam == null) return;
            //get the param list            

            string sQueryId = cmbObjects.SelectedValue.Substring(cmbObjects.SelectedValue.IndexOf("@") + 1);
            DataRow dr = hdd.GetTableRow("select * from sy_report_sql where report_base_id=" + sQueryId);
            Hashtable hsParam = new Hashtable();
            ArrayList alOrder = new ArrayList();
            HtmlTable tmpTable = null;
            if (dr != null)
            {
                //CommonFunctions.decodeData(dr); // Added by 'Imran Gani' on 29-Oct-12, to decode the datarow.
                string sSql = dr["report_base_sql"].ToString();
                string param = dr["report_base_param"].ToString();

                BuildParameters bpObj = new BuildParameters();
                string HorizontailParam = hdd.GetColumnValue("select mem_value1 from sy_acr_mem where acr_id = 'bfbd5b18ed9b6cc1' and af_row_id = 'd2c84d1a2d5910b0';");
                if (HorizontailParam.ToLower() == "enabled") // Added by 'Imran Gani' on 21-Jan-14, for Horizontal parameters.
                {
                    tmpTable = bpObj.createHorizontalParameters(sSql, param, Master.FindControl("ContentPlaceHolder3").FindControl("wz_report"), "", false);
                    tblParam.Width = "100%";
                }
                else
                    tmpTable = bpObj.createParameters(sSql, param, Master.FindControl("ContentPlaceHolder3").FindControl("wz_report"), "", false);

                //string sQueryName = cmbObjects.SelectedItem.Text;
                //if (param.Trim() == "")
                //{
                //    if (sSql.Contains("$") || sSql.Contains("#"))
                //    {
                //        getParameters("$", ref hsParam, sSql);
                //        getParameters("#", ref hsParam, sSql);
                //    }
                //}
                //else
                //{
                //    if (param.Trim().ToLower().StartsWith("parameters"))
                //        param = param.Substring("parameters".Length + 1).Trim();

                //    foreach (string str1 in param.Split(','))
                //    {
                //        if (str1.Trim() == "") continue;
                //        if (str1.Trim() == "") continue;

                //        if (str1.IndexOf("=") == -1)
                //        {
                //            hsParam.Add(str1.Trim(), getDefaultValue(str1.Substring(str1.IndexOf("]") + 1).Trim()));
                //            alOrder.Add(str1.Trim());
                //        }
                //        else
                //        {
                //            hsParam.Add(str1.Substring(0, str1.IndexOf("=")).Trim(), str1.Substring(str1.IndexOf("=") + 1).Trim());
                //            alOrder.Add(str1.Substring(0, str1.IndexOf("=")).Trim());
                //        }
                //    }
                //}
                //dr = null;
            }
            //if (hsParam.Count > 0)
            //{
                tblParam.Border = 0;
                tblParam.CellPadding = 0;
                tblParam.CellSpacing = 0;

                HtmlTableRow htRow = new HtmlTableRow();
                HtmlTableCell htCell = new HtmlTableCell();
                HyperLink hLink = new HyperLink();
                HtmlImage img = new HtmlImage();
                img.ID = "imgParam";
                img.Src = "images/collapse3.gif";//collapse3
                img.Attributes.Add("onClick", "javascript:showHide('ctl00_ContentPlaceHolder3_wz_Report_paramRow'); return false;");
                //img.Align = "texttop";

                hLink.NavigateUrl = "#";
                hLink.Text = "Enter parameter value(s) ";
                hLink.CssClass = "controlLabelFont";
                hLink.Style.Add(HtmlTextWriterStyle.Cursor, "pointer");
                hLink.Style.Add(HtmlTextWriterStyle.TextDecoration, "none");
                hLink.Style.Add(HtmlTextWriterStyle.VerticalAlign, "middle");
                hLink.Attributes.Add("onClick", "javascript:showHide('ctl00_ContentPlaceHolder3_wz_Report_paramRow'); return false;");
                htCell.Controls.Add(hLink);
                htCell.NoWrap = true;
                htCell.Style.Add(HtmlTextWriterStyle.PaddingLeft, "2");
                htCell.Style.Add("Cellspacing" , "0");
                htCell.Controls.Add(img);
                htCell.Attributes.Add("class", "displaygridbottom");
                htRow.Height = "25px";
                htRow.Cells.Add(htCell);
                tblParam.Rows.Add(htRow);

                htRow = new HtmlTableRow();
                htRow.ID = "paramRow";
                //htRow.Style.Add(HtmlTextWriterStyle.Display, "block"); // Commented by 'Imran Gani' on 22-Jan-2014.
                htCell = new HtmlTableCell();
                HtmlTable httTable = new HtmlTable();
                httTable.Border = 0;
                httTable.CellPadding = 0;
                httTable.CellSpacing = 0;

                //HtmlTableRow httRow = new HtmlTableRow();
                //Label lbl1 = new Label();
                //lbl1.Text = "Parameter";
                //lbl1.CssClass = "controlLabelFont";
                //Label lbl2 = new Label();
                //lbl2.Text = "Value";
                //lbl2.CssClass = "controlLabelFont";
                //HtmlTableCell httCell1 = new HtmlTableCell();
                //HtmlTableCell httCell2 = new HtmlTableCell();
                //httCell1.Controls.Add(lbl1);
                ////httCell1.Attributes.Add("class", "displaygridbottom");
                //httCell2.Controls.Add(lbl2);
                ////httCell2.Attributes.Add("class", "displaygridbottom");
                //httRow.Cells.Add(httCell1);
                //httRow.Cells.Add(httCell2);
                //httTable.Rows.Add(httRow);

                #region Code commented
                /*                
                if (alOrder.Count == 0)
                {
                    int iCnt = 1;
                    foreach (string key in hsParam.Keys)
                    {
                        if (key.Trim().StartsWith("$") || key.Trim().StartsWith("#"))
                        {
                            string ch = key.StartsWith("$") ? "$" : "#";
                            lbl1 = new Label();
                            lbl1.Text = key.Replace(ch, "");
                            lbl1.CssClass = "controlLabelFont";
                            lbl1.ID = "lbl_" + key;
                            httRow = new HtmlTableRow();
                            httCell1 = new HtmlTableCell();
                            httCell1.Align = "left";
                            httCell1.Controls.Add(lbl1);
                            httRow.Cells.Add(httCell1);
                            TextBox txt = new TextBox();
                            txt.ID = "txt_param_" + iCnt.ToString();
                            txt.CssClass = "controlFont controlWidth";
                            httCell2 = new HtmlTableCell();
                            httCell2.Controls.Add(txt);
                            httRow.Cells.Add(httCell2);
                            httTable.Rows.Add(httRow);
                            if (key.StartsWith("#"))
                                addAjaxCalendarDate(txt.ID, ref httCell2);
                            iCnt++;
                        }
                    }
                }
                else
                {
                    foreach (string key in alOrder)
                    {
                        string parName = key.Substring(0, key.LastIndexOf("["));
                        string par = key.Replace(parName, "").Replace("[", "").Replace("]", "");
                        string[] pars = par.Split('.');
                        DataTable dt = hdd.GetDataTable("select * from sy_pg_ctr where page_id=(select af_row_id from sy_pg where [page_table_name]='" + pars[0] + "') and control_attrib_id='" + pars[1] + "'");
                        if (dt.Rows.Count > 0)
                        {
                            lbl1 = new Label();
                            lbl1.Text = parName.Replace("[", "").Replace("]", "");// dt.Rows[0]["control_name"].ToString();
                            lbl1.CssClass = "controlLabelFont";
                            lbl1.ID = "lbl_" + key;
                            httRow = new HtmlTableRow();
                            httCell1 = new HtmlTableCell();
                            httCell1.Align = "left";
                            httCell1.Controls.Add(lbl1);
                            httRow.Cells.Add(httCell1);

                            //creating control based on control_html
                            //EM,DD,TA,AN,TB,CB,DDE,PW

                            httCell2 = new HtmlTableCell();
                            switch (dt.Rows[0]["control_html"].ToString().ToUpper())
                            {
                                case "AN":
                                case "EM":
                                case "PW":
                                case "TA":
                                case "TB":
                                    TextBox txt = new TextBox();
                                    txt.ID = "txt_" + key;
                                    txt.CssClass = "controlFont controlWidth";
                                    if (dt.Rows[0]["control_html"].ToString().ToUpper() == "TA")
                                        txt.TextMode = TextBoxMode.MultiLine;
                                    if (hsParam[key].ToString().Trim() == "''" || (hsParam[key].ToString().Trim() == "0"))
                                        txt.Text = "";
                                    else
                                        txt.Text = hsParam[key].ToString();

                                    httCell2.Controls.Add(txt);
                                    if (dt.Rows[0]["control_html"].ToString().ToUpper() == "PW")
                                    {
                                        txt.TextMode = TextBoxMode.Password;
                                        Literal l = new Literal();
                                        l.Text = "&nbsp;<img src=\"Images/key.gif\" alt=\"Password Field\" border=\"0\" />";
                                        httCell2.Controls.Add(l);
                                    }
                                    if (dt.Rows[0]["control_bind_id"].ToString() != "")
                                    {
                                        DataTable dtTmp = hdd.GetDataTable("select * from sy_bnd where af_row_id = '" + dt.Rows[0]["control_bind_id"].ToString() + "';");
                                        if (dtTmp.Rows.Count > 0)
                                        {
                                            Image imgParam = new Image();
                                            imgParam.ID = "imglookup";
                                            imgParam.ImageUrl = "~/Images/search.gif";
                                            imgParam.ToolTip = "Click here for Lookup Window";
                                            imgParam.CssClass = "SearchPopup";
                                            httCell2.Controls.Add(imgParam);

                                            HiddenField hfTxt = new HiddenField();
                                            httCell2.Controls.Add(hfTxt);
                                            hfTxt.ID = "hf_" + key;
                                            imgParam.Attributes.Add("onclick", "javascript:openlookupwindow('wz_Report_" + hfTxt.ID + "','wz_Report_" + txt.ID + "'," + dt.Rows[0]["control_bind_id"].ToString() + ");");
                                        }
                                    }
                                    if (dt.Rows[0]["control_attrib_type"].ToString().ToUpper() == "DA")
                                    {
                                        char[] trimCh = { '\'' };
                                        if (txt.Text.StartsWith("'") && txt.Text.EndsWith("'"))
                                            txt.Text = txt.Text.TrimStart(trimCh).TrimEnd(trimCh);
                                        addAjaxCalendarDate(txt.ID, ref httCell2);
                                    }
                                    else if (dt.Rows[0]["control_attrib_type"].ToString().ToUpper() == "DT")
                                    {
                                        char[] trimCh = { '\'' };
                                        if (txt.Text.StartsWith("'") && txt.Text.EndsWith("'"))
                                            txt.Text = txt.Text.TrimStart(trimCh).TrimEnd(trimCh);
                                        addAjaxCalendarDateTime(txt.ID, ref httCell2);
                                    }
                                    break;
                                case "CB":
                                    CheckBox cb = new CheckBox();
                                    cb.ID = "cb_" + key;
                                    cb.CssClass = "controlFont controlWidth";
                                    cb.Checked = Convert.ToBoolean(hsParam[key].ToString().Replace("'", ""));
                                    httCell2.Controls.Add(cb);
                                    break;
                                case "DD":
                                case "DDE":
                                    DropDownList dd = new DropDownList();
                                    dd.CssClass = "controlFont controlWidth";
                                    dd.ID = "dd_" + key;
                                    dd.Text = hsParam[key].ToString();
                                    httCell2.Controls.Add(dd);
                                    if (dt.Rows[0]["control_bind_id"].ToString() != "")
                                    {
                                        DataTable dtTmp = hdd.GetDataTable("select * from sy_bnd where af_row_id = '" + dt.Rows[0]["control_bind_id"].ToString() + "';");
                                        if (dtTmp.Rows.Count > 0)
                                        {
                                            BindControl bc = new BindControl();
                                            bc.Bind(dt.Rows[0]["control_bind_id"].ToString(), dd, ref dtTmp, dt.Rows[0]);
                                        }
                                    }
                                    break;
                                case "DT":
                                case "DA":
                                    TextBox dadt = new TextBox();
                                    dadt.CssClass = "controlFont controlWidth";
                                    dadt.Text = hsParam[key].ToString();
                                    dadt.ID = "dt_" + key;
                                    if (dt.Rows[0]["control_html"].ToString().ToUpper() == "DA")
                                        addAjaxCalendarDate(dadt.ID, ref httCell2);
                                    else
                                        addAjaxCalendarDateTime(dadt.ID, ref httCell2);
                                    break;
                            }
                            httRow.Cells.Add(httCell2);
                            httTable.Rows.Add(httRow);
                        }
                        dt = null;
                    }
                }
                */
                #endregion

                //htCell.Controls.Add(httTable);
                if (tmpTable != null)
                {
                    htCell = new HtmlTableCell();
                    htCell.Controls.Add(tmpTable);
                    htRow.Cells.Add(htCell);
                    httTable.Rows.Add(htRow);
                }

                //httTable = new HtmlTable();
                //httTable.Border = 1;
                //httTable.CellSpacing = 0;
                //httTable.CellPadding = 0;
                //HtmlTableRow httRow = new HtmlTableRow();
                //HtmlTableCell httCell1 = new HtmlTableCell();
                //Button btnGen = new Button();
                //btnGen.Text = "Generate Report";
                //httCell1.Align = "Center";
                //btnGen.Click += new EventHandler(btnGen_Click);
                //btnGen.CssClass = "controlLabelFont";
                //httCell1.Controls.Add(btnGen);
                //if (tmpTable != null)
                //    httCell1.Width = tmpTable.Width;
                //httRow.Cells.Add(httCell1);
                //httTable.Rows.Add(httRow);

                //httRow = new HtmlTableRow();
                //httCell1 = new HtmlTableCell();
                //LiteralControl lc = new LiteralControl();
                //lc.Text = "";
                //httCell1.Controls.Add(lc);
                //httRow.Cells.Add(httCell1);
                //httRow.Height = "5px";
                //httTable.Rows.Add(httRow);
                //htCell.Controls.Add(httTable);
                //htRow.Cells.Add(htCell);
                tblParam.Rows.Add(htRow);

                htRow = new HtmlTableRow();
                HtmlTableCell httCell = new HtmlTableCell();
                Button btnGen = new Button();
                btnGen.ID = "btnGen";
                btnGen.Text = "Generate Report";
                btnGen.Attributes.Add("style", "margin-bottom:3px;");
                httCell.Align = "Center";
                btnGen.Click += new EventHandler(btnGen_Click);
                btnGen.CssClass = "controlLabelFont";
                httCell.Controls.Add(btnGen);
                htRow.Cells.Add(httCell);
                tblParam.Rows.Add(htRow);
                tblParam.Visible = true;
            //}
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("createParameters : Error : " + ex.Message);
        }
    }

    private string[] GetBindFields(string strBindRowID, string bindvalue, string bindtext, bool includepageid)
    {
        HDDatabase HDD = new HDDatabase();
        string[] arr = new string[5];
        try
        {
            string sql = "select * From sy_bnd where af_row_id = '" + strBindRowID + "';";
            string strPagesetRowId = HDD.GetColumnValue("select C.af_row_id from sy_bnd A, sy_pg B, sy_pgs C, sy_pgs_mem D where A.bind_table = B.page_table_name and B.page_id = D.page_id and C.af_row_id = D.pageset_id and A.af_row_id = '" + strBindRowID + "'");
            string strMenuRowId = HDD.GetColumnValue("select af_row_id from sy_mnu where pageset_id = '" + strPagesetRowId + "'");
            string page_id = HDD.GetColumnValue("select B.page_id from sy_pgs A, sy_pgs_mem B where A.af_row_id = B.pageset_id and A.af_row_id = '" + strPagesetRowId + "'");
            DataTable dt = HDD.GetDataTable(sql);
            if (dt != null)
                if (dt.Rows.Count > 0)
                {
                    if (includepageid)
                    {
                        arr[0] = page_id + "_" + bindvalue;
                        arr[1] = page_id + "_" + bindtext;
                    }
                    else
                    {
                        arr[0] = bindvalue;
                        arr[1] = bindtext;
                    }
                }
            arr[2] = strPagesetRowId;
            arr[3] = strMenuRowId;
            arr[4] = page_id;
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : GetBindFields : " + ex.Message);
        }
        return arr;
    }

    private void addAjaxCalendarDate(string id, ref HtmlTableCell htc)
    {
        if (id.Length < 1) return;
        CalendarExtender ce = new CalendarExtender();        
        ce.ID = "ce_ajax_" + id;
        //ce.Format = getUserDateFormat();
        ce.TargetControlID = id;
        ce.OnClientShowing = "hideC1Report";
        ce.OnClientHidden = "showC1Report";
        htc.Controls.Add(ce);
    }

    private void addAjaxCalendarDateTime(string id, ref HtmlTableCell htc)
    {
        if (id.Length < 1) return;
        CalendarExtender ce = new CalendarExtender();
        ce.ID = "ce_ajax_" + id;
        //ce.Format = getUserDateFormat() + " hh:mm tt";
        ce.OnClientShowing = "hideC1Report";
        ce.OnClientHidden = "showC1Report";
        ce.TargetControlID = id;        
        htc.Controls.Add(ce);
    }

    private string getUserDateFormat()
    {
        #region Old code commented by 'Imran Gani' on 28-Feb-2014, for MBLocale
        //Localization ll = new Localization();
        //string ret = ll.getDateFormat();
        //ll = null;
        #endregion
        string ret = MBLocalization.getDateFormat(HttpContext.Current.Session["userlocale"].ToString());
        return ret;
    }

    void btnGen_Click(object sender, EventArgs e)
    {
        try
        {
            DataRow dr = hdd.GetTableRow("select * from sy_report_sql where report_base_id=" + cmbObjects.SelectedValue.Substring(cmbObjects.SelectedValue.IndexOf("@") + 1));
            Hashtable hsParam = new Hashtable();
            if (dr != null)
            {
                //CommonFunctions.decodeData(dr); // Added by 'Imran Gani' on 29-Oct-12, to decode the datarow.
                hsParam = updateParameters(dr["report_base_sql"].ToString(), dr["report_base_param"].ToString());
            }
            if (hsParam.Count > 0)
                Session["param"] = hsParam;
            dr = null;
            wz_Report.ActiveStepIndex = 6;
            if (Session["showReport"] == null)
                Session.Add("showReport", true);

            generateReport(false, "");

            bool IsExport = getExportValue();
            if (IsExport)
            {
                lblExport.Visible = true;
                ddlExport.Visible = true;
                lnkExport.Visible = true;
            }
            else
            {
                lblExport.Visible = false;
                ddlExport.Visible = false;
                lnkExport.Visible = false;
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("btnGen_Click : Error : " + ex.Message);
        }
    }

    private void isViewMode()
    {
        if (HttpContext.Current.Request.QueryString["VMODE"] != null)
            if (HttpContext.Current.Request.QueryString["VMODE"] == "1")
            {
                IsEdit = true;
                wz_Report.ActiveStepIndex = 6;
                //        wz_Report.ActiveStepIndex = 5;
                DynamicDisplayI ddI = new DynamicDisplayI();
                Button btn = (Button)ddI.FindControl(Master.FindControl("ContentPlaceHolder3").FindControl("wz_report").Controls, "FinishPreviousButton");
                if (btn != null)
                    btn.Visible = false;
                ddI = null;
                //        //reportViewer.Report.Load(Server.MapPath(".") + "\\report\\" + hf_af_row_id1.Value + ".xml", txtRepName.Text);
                //    }
                //    else
                //        LogWriter.WriteLog("isViewMode: Error: Report is not generated");
                //}
                //if (generateReportXML(dsReport))
                //{
                //    if (File.Exists(Server.MapPath(".") + "\\report\\" + hf_af_row_id1.Value + ".xml"))
                //    {
                //        wz_Report.ActiveStepIndex = 5;

                //        DynamicDisplayI ddI = new DynamicDisplayI();
                //        Button btn = (Button)ddI.FindControl(Master.FindControl("ContentPlaceHolder3").FindControl("wz_report").Controls, "FinishPreviousButton");
                //        if (btn != null)
                //            btn.Enabled = false;
                //        ddI = null;
                //        reportViewer.Report.Load(Server.MapPath(".") + "\\report\\" + hf_af_row_id1.Value + ".xml", txtRepName.Text);
                //    }
                //    else
                //        LogWriter.WriteLog("btnPreview_Click: Error: Report file is not found");
                //}
            }
    }

    private bool checkEditCopyOperation()
    {
        bool blnStatus = true;

        if (!IsPostBack)
        {
            if (Request.QueryString["PK"] != null)
            {
                IsEdit = true;
                if (Request.QueryString["CPY"] != null)
                {
                    if (Request.QueryString["CPY"] == "0")
                    {
                        IsEdit = false;
                        ScreenReader SR = new ScreenReader();
                        hf_af_row_id1.Value = SR.getHashKey();
                    }
                }
                getData();
                setData(IsEdit);
            }
        }
        return blnStatus;
    }

    private void deleteReport()
    {
        if (hfRName.Value != "")
        {
            if (System.IO.File.Exists(hfRName.Value))
                System.IO.File.Delete(hfRName.Value);
            hfRName.Value = "";
        }
    }

    protected void wizReport_FinishButtonClick(object sender, WizardNavigationEventArgs e)
    {
        try
        {
            if (!IsEdit)
            {
                if (dsReport.Tables["p_sy_report"].Columns["rpt_id"] != null)
                    dsReport.Tables["p_sy_report"].Columns.Remove("rpt_id");
            }
            //m_PageKey = hf_af_row_id1.Value;
            //m_Report_id = hdd.GetColumnValue("select rpt_id from sy_report where af_row_id = '" + m_PageKey + "'");
            //IsEdit = true;
            //setData(IsEdit);
            if (SaveData())
            {
                EventArgs e1 = new EventArgs();
                wz_Report_CancelButtonClick(sender, e1);
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("wizReport_FinishButtonClick : Error : " + ex.Message);
        }
    }

    private void setFieldValues()
    {
        DataTable dt = (DataTable)Session["FieldProperties"];
        Session["FieldProperties"] = null;
        if (dsReport != null)
            if (dsReport.Tables["p_sy_report_att"] != null)
                if (dt == null)
                    dt = dsReport.Tables["p_sy_report_att"];
        if (dt != null)
        {
            for (int iCount = 0; iCount < lstSelectedFields1.Items.Count; iCount++)
            {
                ListItem li = lstSelectedFields1.Items[iCount];
                TextBox txtBox = (TextBox)this.Master.FindControl("ContentPlaceHolder3").FindControl("wz_report").FindControl("txt_" + li.Value);
                DataRow[] drr = dt.Select("attrib_id='" + li.Value + "'");

                if (drr.Length != 0)
                {
                    txtBox.Text = drr[0]["caption"].ToString();
                }
            }
            dt.Dispose();
            dt = null;
        }
    }

    private void ProcessDataTable(ref DataTable dtData)
    {
        DynamicDisplayI DDI = new DynamicDisplayI();
        try
        {
            string sUTC_Offset = DDI.getUserSetting("sy_usr", "time_zone", "sy_timezone", "utc_offset", "timezone_id");

            foreach (DataColumn dc in dtData.Columns)
                if (dc.DataType == Type.GetType("System.DateTime"))
                {
                    foreach (DataRow dr in dtData.Rows)
                    {
                        if (dr[dc.ColumnName] != System.DBNull.Value)
                            dr[dc.ColumnName] = DDI.getUsersDT(dr[dc.ColumnName].ToString(), sUTC_Offset);
                    }
                }

        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("ProcessDataTable : Error : " + ex.Message);
        }
        finally
        {
            DDI = null;
        }
    }

    private DataTable getDataForReport(string Query)
    {
        DataTable dtData = new DataTable();
        SqlDataAdapter objAdapter = null;
        SqlConnection sqlConn = null;
        SqlCommand command = null;
        try
        {
            sqlConn = new SqlConnection(HttpContext.Current.Session["dbcon"].ToString());
            sqlConn.Open();
            command = sqlConn.CreateCommand();
            command.CommandText = Query;
            objAdapter = new SqlDataAdapter(command);
            objAdapter.Fill(dtData);
            sqlConn.Close();

            //if (dtData.Rows.Count > 0 && dtData.Columns.Contains("created_by"))
            // Added by srivatsan on June 15 2009 for owner id field
            if (dtData.Rows.Count > 0 && dtData.Columns.Contains("owner_id"))
            {
                SecurityFilter SF = new SecurityFilter();
                DataSet dseObj = SF.GetFilterDataset(Query);
                dtData = dseObj.Tables[0].Copy();
                dseObj.Dispose();
                dseObj = null;
            }

            ProcessDataTable(ref dtData);
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("getDataSet : Error : " + ex.Message);
            dtData = null;
        }

        finally
        {
            objAdapter.Dispose();
            sqlConn.Dispose();
            command.Dispose();
            objAdapter = null;
            sqlConn = null;
            command = null;
        }
        return dtData;
    }

    private DataTable getDataTable()
    {
        DataTable dt = new DataTable();
        dt.Columns.Add("attrib_id");
        dt.Columns.Add("caption");
        dt.Columns.Add("bold");
        dt.Columns.Add("wrap");
        return dt;
    }

    private void collectValuesFromDS()
    {
        DataTable dtValues = getDataTable();

        foreach (DataRow drr in dsReport.Tables["p_sy_report_att"].Rows)
        {
            DataRow dr = dtValues.NewRow();
            dr["attrib_id"] = "[" + drr["object_id"].ToString() + "].[" + drr["attrib_id"].ToString() + "]";
            dr["caption"] = drr["caption"];
            dtValues.Rows.Add(dr);
        }
        Session["FieldProperties"] = dtValues;
    }

    private void collectValues()
    {
        DataTable dtValues = getDataTable();
        for (int iCount = 0; iCount < lstSelectedFields1.Items.Count; iCount++)
        {
            ListItem li = lstSelectedFields1.Items[iCount];

            TextBox txtBox = (TextBox)this.Master.FindControl("ContentPlaceHolder3").FindControl("wz_report").FindControl("txt_" + li.Value);
            string sCaption = "";
            if (txtBox != null)
                sCaption = txtBox.Text;
            else
                sCaption = li.Text;

            DataRow dr = dtValues.NewRow();
            dr["attrib_id"] = li.Value;
            dr["caption"] = sCaption;

            DropDownList dd1 = (DropDownList)this.Master.FindControl("ContentPlaceHolder3").FindControl("wz_report").FindControl("dd_" + li.Value + "_bold");
            if (dd1 != null)
                sCaption = dd1.Text;
            else
                sCaption = "No";
            dr["bold"] = sCaption;

            dd1 = (DropDownList)this.Master.FindControl("ContentPlaceHolder3").FindControl("wz_report").FindControl("dd_" + li.Value + "_wwrap");
            if (dd1 != null)
                sCaption = dd1.Text;
            else
                sCaption = "No";
            dr["wrap"] = sCaption;

            dtValues.Rows.Add(dr);
        }

        Session["FieldProperties"] = dtValues;
    }

    private void createDataTable(int stepIdx, ref DataSet dsReport)
    {
        DataTable dtRet = new DataTable();
        try
        {
            switch (stepIdx)
            {
                case 0:
                    dtRet.TableName = "p_sy_report";
                    dtRet.Columns.Add("af_row_id");
                    dtRet.Columns.Add("rpt_base_object");
                    dtRet.Columns.Add("rpt_name");
                    dtRet.Columns.Add("rpt_desc");
                    dtRet.Columns.Add("report_category"); // Added by 'Imran Gani' on 28-May-2012, for report category.
                    dtRet.Columns.Add("source_filter_grouping"); // Added by Imran Gani on 20-Jul-2012, for Source Filter.
                    //dtRet.Columns.Add("rpt_src_id");
                    //dtRet.Columns.Add("ownerid");
                    dsReport.Tables.Add(dtRet);

                    dtRet = new DataTable("p_sy_report_obj");
                    dtRet.Columns.Add("af_row_id");
                    dtRet.Columns.Add("rpt_id");
                    dtRet.Columns.Add("object_id");

                    break;
                case 1:
                    dtRet.TableName = "p_sy_report_att";
                    dtRet.Columns.Add("af_row_id");
                    //dtRet.Columns.Add("rpt_src_id");
                    dtRet.Columns.Add("attrib_id");
                    dtRet.Columns.Add("caption");
                    dtRet.Columns.Add("is_bold");
                    dtRet.Columns.Add("is_wrap");
                    break;
                case 2: // Added by Imran Gani on 20-Jul-2012, for Source Filter.
                    dtRet.TableName = "p_report_source_filter";
                    dtRet.Columns.Add("af_row_id");
                    dtRet.Columns.Add("sequence");
                    dtRet.Columns.Add("field");
                    dtRet.Columns.Add("condition");
                    dtRet.Columns.Add("field_value");
                    dtRet.Columns.Add("source_object");
                    dtRet.Columns.Add("rpt_id");
                    break;
                case 3:
                    dtRet = new DataTable("p_report_grouping");
                    dtRet.Columns.Add("af_row_id");
                    //dtRet.Columns.Add("rpt_src_id");
                    dtRet.Columns.Add("attribute_sequence");
                    //dtRet.Columns.Add("rpt_group_length");
                    dtRet.Columns.Add("grouping_field");
                    dtRet.Columns.Add("grouping_order");
                    dtRet.Columns.Add("show_header");
                    dtRet.Columns.Add("show_subtotal");
                    dsReport.Tables.Add(dtRet);

                    dtRet = new DataTable("p_report_grouping_header");
                    dtRet.Columns.Add("af_row_id");
                    dtRet.Columns.Add("rpt_group_id");
                    dtRet.Columns.Add("header_field");
                    dtRet.Columns.Add("group_sequence");
                    dtRet.Columns.Add("field_sequence");
                    dsReport.Tables.Add(dtRet);

                    dtRet = new DataTable("p_report_grouping_subtotal");
                    dtRet.Columns.Add("af_row_id");
                    dtRet.Columns.Add("rpt_group_id");
                    dtRet.Columns.Add("subtotal_field");
                    dtRet.Columns.Add("group_sequence");
                    dtRet.Columns.Add("field_sequence");
                    dsReport.Tables.Add(dtRet);

                    #region commented for phase 1
                    //dtRet = new DataTable("step3_report_grouping_sort_details");
                    //dtRet.Columns.Add("af_row_id");
                    //dtRet.Columns.Add("rpt_group_id");
                    //dtRet.Columns.Add("sort_detail_field");
                    //dtRet.Columns.Add("attribute_sequence");
                    //dtRet.Columns.Add("sort_detail_order");
                    //dsReport.Tables.Add(dtRet);
                    #endregion

                    dtRet = new DataTable("p_report_grouping_grand_total");
                    dtRet.Columns.Add("af_row_id");
                    dtRet.Columns.Add("rpt_group_id");
                    dtRet.Columns.Add("grand_total_field");
                    dtRet.Columns.Add("attribute_sequence");
                    break;
                case 4:
                    dtRet.TableName = "p_report_header_footer";
                    dtRet.Columns.Add("rpt_id");
                    dtRet.Columns.Add("af_row_id");
                    dtRet.Columns.Add("rpt_title");
                    dtRet.Columns.Add("rpt_head_text");
                    dtRet.Columns.Add("rpt_foot_text");
                    dtRet.Columns.Add("rpt_logo");
                    dtRet.Columns.Add("rpt_date");
                    dtRet.Columns.Add("rpt_page_no");
                    break;
                default:
                    break;
            }
            if (!dsReport.Tables.Contains(dtRet.TableName))
                dsReport.Tables.Add(dtRet);
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("createDataTable : Error : " + ex.Message);
        }
    }

    private string convertText(string inpStr)
    {
        string outStr=inpStr;
        try
        {
            if (inpStr.Trim() == "---None---")
                outStr = "";
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("convertText : Error : " + ex.Message);
        }
        return outStr;
    }

    private void validateSelGrouping(ref DataTable dt, bool flag)
    {
        DataTable dtR = new DataTable();
        try
        {
            if (dt.Rows.Count == 0) return;
            dtR = dt.Clone();
            if (IsEdit)
            {
                for (int iCount = 0; iCount < lstSelectedFields1.Items.Count; iCount++)
                {
                    ListItem li = lstSelectedFields1.Items[iCount];
                    DataRow[] drF = dt.Select("grouping_field='" + li.Value + "'");
                    if (drF.Length > 0)
                        dtR.ImportRow(drF[0]);
                    else
                    {
                        if (li.Value.IndexOf("].[") != -1)
                        {
                            drF = dt.Select("grouping_field='" + li.Value.Substring(li.Value.IndexOf("].[") + 3).Replace("]", "") + "'");
                            if (drF.Length > 0)
                                dtR.ImportRow(drF[0]);
                        }
                    }
                    drF = null;
                }
            }
            else
            {
                for (int iCount = 0; iCount < Convert.ToInt32(hiddenGroupCnt.Value); iCount++)
                {
                    DropDownList ddl = (DropDownList)this.Master.FindControl("ContentPlaceHolder3").FindControl("wz_report").FindControl("PlaceHolder_group").FindControl("ddl_group_field_" + (iCount + 1).ToString());
                    if (ddl != null)
                    {
                        if (convertText(ddl.SelectedValue) == "") continue;
                        DataRow[] drF = dt.Select("grouping_field='" + convertText(ddl.SelectedValue) + "'");
                        if (drF.Length > 0)
                            dtR.ImportRow(drF[0]);
                        drF = null;
                    }
                }
            }
            if (dtR.Rows.Count > 0)
            {
                dt.Rows.Clear();
                dt.Merge(dtR);
            }
            dtR = null;
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("validateSelGrouping : Error : " + ex.Message);
        }
        return;
    }

    private void validateSelGroupingHdrSub(ref DataTable dt, string ddlHdrSub, string fieldName)
    {
        DataTable dtR = new DataTable();
        try
        {
            if (dt.Rows.Count == 0) return;
            dtR = dt.Clone();
            if (IsEdit)
            {
                for (int iCount = 0; iCount < lstSelectedFields1.Items.Count; iCount++)
                {
                    ListItem li = lstSelectedFields1.Items[iCount];
                    DataRow[] drF = dt.Select(fieldName + "_field='" + li.Value + "'");
                    if (drF.Length > 0)
                    {
                        foreach(DataRow drr in drF)
                            dtR.ImportRow(drr);
                    }
                    else
                    {
                        if (li.Value.IndexOf("].[") != -1)
                        {
                            drF = dt.Select(fieldName + "_field='" + li.Value.Substring(li.Value.IndexOf("].[") + 3).Replace("]", "") + "'");
                            if (drF.Length > 0)
                                dtR.ImportRow(drF[0]);
                        }
                    }
                    drF = null;
                }
            }
            else
            {
                dtR = dt.Clone();
                for (int iCount = 0; iCount < Convert.ToInt32(hiddenGroupCnt.Value); iCount++)
                {
                    for (int k = 1; k <= 3; k++)
                    {
                        DropDownList ddl = (DropDownList)this.Master.FindControl("ContentPlaceHolder3").FindControl("wz_report").FindControl("PlaceHolder_group").FindControl("ddl_" + ddlHdrSub + "_field" + k.ToString() + "_" + (iCount + 1).ToString()); // "hdr"/"tot"
                        if (ddl != null)
                        {
                            if (convertText(ddl.SelectedValue) == "") continue;
                            DataRow[] drF = dt.Select(fieldName + "_field='" + convertText(ddl.SelectedValue) + "'");
                            if (drF.Length > 0)
                                dtR.ImportRow(drF[0]);
                            drF = null;
                        }
                    }
                }
            }
            if (dtR.Rows.Count > 0)
            {
                dt.Rows.Clear();
                dt.Merge(dtR);
            }
            dtR = null;
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("validateSelGroupingHdrSub : Error : " + ex.Message);
        }
        return;
    }

    private void validateSelGrandTotal(ref DataTable dt)
    {
        DataTable dtR = new DataTable();
        try
        {
            if (dt.Rows.Count == 0) return;

            dtR = dt.Clone();
            for (int j = 1; j <= 3; j++)
            {
                string tmp = "";
                if (j == 1)
                    tmp = convertText(ddl_grtot_field1.SelectedValue);
                else if (j == 2)
                    tmp = convertText(ddl_grtot_field2.SelectedValue);
                else if (j == 3)
                    tmp = convertText(ddl_grtot_field3.SelectedValue);
                if (tmp.Trim() == "") continue;

                DataRow[] drF = dt.Select("grand_total_field='" + tmp + "'");
                if (drF.Length > 0)
                    dtR.ImportRow(drF[0]);
                drF = null;
            }
            if (dtR.Rows.Count > 0)
            {
                dt.Rows.Clear();
                dt.Merge(dtR);
            }
            dtR = null;
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("validateSelGrandTotal : Error : " + ex.Message);
        }
    }

    private void validateSelFields(ref DataTable dt)
    {
        DataTable dtR = new DataTable();
        try
        {
            if (dt.Rows.Count == 0) return;
            if (dt.Rows.Count == lstSelectedFields1.Items.Count)
            {
                if (IsEdit)
                {
                    dtR = dt.Clone();
                    for (int iCount = 0; iCount < lstSelectedFields1.Items.Count; iCount++)
                    {
                        ListItem li = lstSelectedFields1.Items[iCount];
                        DataRow[] drF = dt.Select("attrib_id='" + li.Value + "'");
                        if (drF.Length > 0)
                            dtR.ImportRow(drF[0]);
                        else
                        {
                            if (li.Value.IndexOf("].[") != -1)
                            {
                                drF = dt.Select("attrib_id='" + li.Value.Substring(li.Value.IndexOf("].[") + 3).Replace("]", "") + "'");
                                if (drF.Length > 0)
                                    dtR.ImportRow(drF[0]);
                            }
                        }
                        if (drF != null && drF.Length > 0)
                        {
                            TextBox txtBox = (TextBox)this.Master.FindControl("ContentPlaceHolder3").FindControl("wz_report").FindControl("txt_" + li.Value);
                            dtR.Rows[iCount]["caption"] = txtBox.Text;
                            DropDownList dd1 = (DropDownList)this.Master.FindControl("ContentPlaceHolder3").FindControl("wz_report").FindControl("dd_" + li.Value + "_bold");
                            DropDownList dd2 = (DropDownList)this.Master.FindControl("ContentPlaceHolder3").FindControl("wz_report").FindControl("dd_" + li.Value + "_wwrap");
                            dtR.Rows[iCount]["is_bold"] = dd1.Text.ToLower() == "yes" ? "true" : "false";
                            dtR.Rows[iCount]["is_wrap"] = dd2.Text.ToLower() == "yes" ? "true" : "false";
                            drF = null;
                        }
                        else // Added by 'Imran Gani' on 04-Sep-12.
                        {
                            Label lbl = (Label)this.Master.FindControl("ContentPlaceHolder3").FindControl("wz_report").FindControl("lbl_caption_" + li.Value);

                            TextBox txtBox = (TextBox)this.Master.FindControl("ContentPlaceHolder3").FindControl("wz_report").FindControl("txt_" + li.Value);

                            DropDownList dd1 = (DropDownList)this.Master.FindControl("ContentPlaceHolder3").FindControl("wz_report").FindControl("dd_" + li.Value + "_bold");

                            DropDownList dd2 = (DropDownList)this.Master.FindControl("ContentPlaceHolder3").FindControl("wz_report").FindControl("dd_" + li.Value + "_wwrap");

                            DataRow dr = dtR.NewRow();
                            dr["af_row_id"] = "";
                            dr["attrib_id"] = li.Value;
                            dr["caption"] = txtBox.Text;
                            dr["is_bold"] = dd1.Text.ToLower() == "yes" ? "true" : "false";
                            dr["is_wrap"] = dd2.Text.ToLower() == "yes" ? "true" : "false";
                            dtR.Rows.Add(dr);
                        }
                    }
                    dt.Rows.Clear();
                    dt.Merge(dtR);
                    dtR.Rows.Clear();
                }
                else
                {
                    dt.Rows.Clear();
                    for (int k = 0; k < lstSelectedFields1.Items.Count; k++)
                    {
                        ListItem li = lstSelectedFields1.Items[k];
                        Label lbl = (Label)this.Master.FindControl("ContentPlaceHolder3").FindControl("wz_report").FindControl("lbl_caption_" + li.Value);

                        TextBox txtBox = (TextBox)this.Master.FindControl("ContentPlaceHolder3").FindControl("wz_report").FindControl("txt_" + li.Value);

                        DropDownList dd1 = (DropDownList)this.Master.FindControl("ContentPlaceHolder3").FindControl("wz_report").FindControl("dd_" + li.Value + "_bold");

                        DropDownList dd2 = (DropDownList)this.Master.FindControl("ContentPlaceHolder3").FindControl("wz_report").FindControl("dd_" + li.Value + "_wwrap");

                        DataRow dr = dt.NewRow();
                        dr["af_row_id"] = "";
                        dr["attrib_id"] = li.Value;
                        dr["caption"] = txtBox.Text;
                        dr["is_bold"] = dd1.Text.ToLower() == "yes" ? "true" : "false";
                        dr["is_wrap"] = dd2.Text.ToLower() == "yes" ? "true" : "false";
                        dt.Rows.Add(dr);
                    }
                }
                return;
            }
            dtR = dt.Clone();
            if (dt.Rows.Count != lstSelectedFields1.Items.Count)
            {
                for (int iCount = 0; iCount < lstSelectedFields1.Items.Count; iCount++)
                {
                    ListItem li = lstSelectedFields1.Items[iCount];
                    DataRow[] drF = dt.Select("attrib_id='" + li.Value + "'");
                    if (drF.Length > 0)
                        dtR.ImportRow(drF[0]);
                    else
                    {
                        if (li.Value.IndexOf("].[") != -1)
                        {
                            drF = dt.Select("attrib_id='" + li.Value.Substring(li.Value.IndexOf("].[") + 3).Replace("]", "") + "'");
                            if (drF.Length > 0)
                                dtR.ImportRow(drF[0]);
                            else
                            {
                                Label lbl = (Label)this.Master.FindControl("ContentPlaceHolder3").FindControl("wz_report").FindControl("lbl_caption_" + li.Value);

                                TextBox txtBox = (TextBox)this.Master.FindControl("ContentPlaceHolder3").FindControl("wz_report").FindControl("txt_" + li.Value);

                                DropDownList dd1 = (DropDownList)this.Master.FindControl("ContentPlaceHolder3").FindControl("wz_report").FindControl("dd_" + li.Value + "_bold");

                                DropDownList dd2 = (DropDownList)this.Master.FindControl("ContentPlaceHolder3").FindControl("wz_report").FindControl("dd_" + li.Value + "_wwrap");

                                DataRow dr = dtR.NewRow();
                                dr["af_row_id"] = "";
                                dr["attrib_id"] = li.Value;
                                dr["caption"] = txtBox.Text;
                                dr["is_bold"] = dd1.Text.ToLower() == "yes" ? "true" : "false";
                                dr["is_wrap"] = dd2.Text.ToLower() == "yes" ? "true" : "false";
                                dtR.Rows.Add(dr);
                            }
                        }
                    }
                    drF = null;
                }
                dt.Rows.Clear();
                dt.Merge(dtR);
            }
            dtR = null;
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("validateSelFields : Error : " + ex.Message);
        }
    }

    private void substitute_step_values(int stepIdx)
    {
        DataTable dt = new DataTable();
        try
        {
            dsReport = (DataSet)Session["report_ds"];
            if (dsReport == null)
                dsReport = new DataSet(); 

            switch (stepIdx)
            {
                case 0:
                case 5:
                    {
                        if (dsReport.Tables.Contains("p_sy_report"))
                        {
                            dt = dsReport.Tables["p_sy_report"];
                            for (int k = 0; k < dt.Rows.Count; k++)
                            {
                                DataRow dr = dt.Rows[k];
                                lblReportSrc.Text = dr["rpt_base_object"].ToString();
                                txtRepName.Text = dr["rpt_name"].ToString();
                                txtReportDesc.Text = dr["rpt_desc"].ToString();
                                txtReportCategory.Text = dr["report_category"].ToString(); // Added by 'Imran Gani' on 28-May-2012, for report category.
                                //txt_owner_id.Text = dr["ownerid"].ToString();
                                dr = null;
                            }
                        }
                    }
                    break;
                #region Step 2
                case 1:
                    {
                        if (dsReport.Tables.Contains("p_sy_report_att"))
                        {
                            dt = dsReport.Tables["p_sy_report_att"];

                            validateSelFields (ref dt);
                            for (int k = 0; k < dt.Rows.Count; k++)
                            {
                                DataRow dr = dt.Rows[k];

                                Label lbl = (Label)this.Master.FindControl("ContentPlaceHolder3").FindControl("wz_report").FindControl("lbl_caption_" + dr["attrib_id"].ToString());
                                lbl.Text = lstSelectedFields1.Items[k].Text; //dr["attrib_id"].ToString();

                                TextBox txtBox = (TextBox)this.Master.FindControl("ContentPlaceHolder3").FindControl("wz_report").FindControl("txt_" + dr["attrib_id"].ToString());
                                txtBox.Text = dr["caption"].ToString();

                                DropDownList dd1 = (DropDownList)this.Master.FindControl("ContentPlaceHolder3").FindControl("wz_report").FindControl("dd_" + dr["attrib_id"].ToString() + "_bold");
                                if (dr["is_bold"].ToString().ToLower() == "true" || dr["is_bold"].ToString().ToLower() == "false")
                                    dd1.Text = dr["is_bold"].ToString().ToLower() == "true"?"Yes":"No";
                                else
                                    dd1.Text = dr["is_bold"].ToString();

                                dd1 = (DropDownList)this.Master.FindControl("ContentPlaceHolder3").FindControl("wz_report").FindControl("dd_" + dr["attrib_id"].ToString() + "_wwrap");
                                if (dr["is_wrap"].ToString().ToLower() == "true" || dr["is_wrap"].ToString().ToLower() == "false")
                                    dd1.Text = dr["is_wrap"].ToString().ToLower() == "true" ? "Yes" : "No";
                                else
                                    dd1.Text = dr["is_wrap"].ToString();
                            }
                        }
                    }
                    break;
                #endregion

                #region Step 3
                case 2: // Added by Imran Gani on 20-Jul-2012, for Source Filter.
                    hfFilterTable.Value = "";
                    if (dsReport.Tables["p_sy_report"].Rows[0]["rpt_base_object"].ToString().ToLower() == "object")
                    {
                        if (dsReport.Tables.Contains("p_sy_report") && dsReport.Tables["p_sy_report"].Rows.Count > 0)
                            hfFilterGroup.Value = dsReport.Tables["p_sy_report"].Rows[0]["source_filter_grouping"].ToString();
                        if (hfFilterTable.Value != null && hfFilterTable.Value != "")
                        {
                            ScriptManager.RegisterStartupScript(this, this.GetType(), "SrcFilter", "javascript:DisplayTable();", true);
                        }
                        else if (dsReport.Tables.Contains("p_report_source_filter"))
                        {
                            dt = dsReport.Tables["p_report_source_filter"];
                            if (dt != null && dt.Rows.Count > 0)
                            {
                                hfFilterTable.Value = getSourceFilterInputData(dt);
                                ScriptManager.RegisterStartupScript(this, this.GetType(), "SrcFilter", "javascript:DisplayTable();", true);
                            }
                        }
                    }
                    break;
                #endregion

                #region Step 4
                case 3:
                    {
                        for (int i = 1; i <= Convert.ToInt16(hiddenGroupCnt.Value); i++)
                        {
                            DropDownList ddl = (DropDownList)this.Master.FindControl("ContentPlaceHolder3").FindControl("wz_report").FindControl("PlaceHolder_group").FindControl("ddl_group_field_" + (i).ToString());
                            if (ddl != null)
                                populateFieldsFromSelectedList(ref ddl);
                        }

                        string objectId = cmbObjects.SelectedValue.Substring(cmbObjects.SelectedValue.IndexOf("@") + 1);
                        if (dsReport.Tables.Contains("p_report_grouping"))
                        {
                            dt = dsReport.Tables["p_report_grouping"];
                            validateSelGrouping(ref dt, IsEdit);
                            for (int k = 0; k < dt.Rows.Count; k++)
                            {
                                DataRow dr = dt.Rows[k];
                                //Session["groupCount"] = dr["rpt_group_length"];
                                //hiddenGroupCnt.Value = dr["rpt_group_length"].ToString();

                                //Grouping fields
                                DropDownList ddl = (DropDownList)this.Master.FindControl("ContentPlaceHolder3").FindControl("wz_report").FindControl("PlaceHolder_group").FindControl("ddl_group_field_" + (k+1).ToString());
                                if (ddl != null)
                                {
                                    if (dr["grouping_field"].ToString().IndexOf("].[") != -1)
                                        ddl.Text = dr["grouping_field"].ToString();
                                    else
                                        ddl.Text = "[" + objectId + "].[" + dr["grouping_field"].ToString() + "]";
                                }
                                ddl = (DropDownList)this.Master.FindControl("ContentPlaceHolder3").FindControl("wz_report").FindControl("PlaceHolder_group").FindControl("ddl_group_order_" + (k+1).ToString());
                                if (ddl != null)
                                    ddl.SelectedItem.Text = dr["grouping_order"].ToString();

                                //Show header/subtotal
                                CheckBox cb = (CheckBox)this.Master.FindControl("ContentPlaceHolder3").FindControl("wz_report").FindControl("PlaceHolder_group").FindControl("cb_showhdr_" + (k+1).ToString());
                                if (cb != null)
                                    cb.Checked = Convert.ToBoolean(dr["show_header"].ToString());

                                cb = (CheckBox)this.Master.FindControl("ContentPlaceHolder3").FindControl("wz_report").FindControl("PlaceHolder_group").FindControl("cb_showsub_" + (k+1).ToString());
                                if (cb != null)
                                    cb.Checked = Convert.ToBoolean(dr["show_subtotal"].ToString());
                            }
                        }

                        for (int k = 0; k < Convert.ToInt16(hiddenGroupCnt.Value); k++)
                        {
                            for (int j = 1; j <= 3; j++)
                            {
                                DropDownList ddl = (DropDownList)this.Master.FindControl("ContentPlaceHolder3").FindControl("wz_report").FindControl("PlaceHolder_group").FindControl("ddl_hdr_field" + (j).ToString() + "_" + (k+1).ToString());
                                if (ddl != null)
                                    populateFieldsFromSelectedList(ref ddl);
                            }
                        }

                        if (dsReport.Tables.Contains("p_report_grouping_header"))
                        {                            
                            dt = dsReport.Tables["p_report_grouping_header"];
                            validateSelGroupingHdrSub(ref dt, "hdr", "header");
                            for (int k = 0; k < dt.Rows.Count; k++)
                            {
                                foreach (DataRow drr in dt.Select("group_sequence=" + dt.Rows[k]["group_sequence"].ToString()))
                                {
                                    DropDownList ddl = (DropDownList)this.Master.FindControl("ContentPlaceHolder3").FindControl("wz_report").FindControl("PlaceHolder_group").FindControl("ddl_hdr_field" + drr["field_sequence"].ToString() + "_" + drr["group_sequence"].ToString());
                                    if (ddl != null)
                                    {
                                        if (drr["header_field"].ToString().IndexOf("].[") == -1)
                                            ddl.Text = "[" + objectId + "].[" + drr["header_field"].ToString() + "]";
                                        else
                                            ddl.Text = drr["header_field"].ToString();
                                    }
                                }
                            }
                        }
                        
                        for (int k = 0; k < Convert.ToInt16(hiddenGroupCnt.Value); k++)
                        {
                            for (int j = 1; j <= 3; j++)
                            {
                                DropDownList ddl = (DropDownList)this.Master.FindControl("ContentPlaceHolder3").FindControl("wz_report").FindControl("PlaceHolder_group").FindControl("ddl_tot_field" + (j).ToString() + "_" + (k + 1).ToString());
                                if (ddl != null)
                                    populateNumericFields(ref ddl, objectId);
                            }
                        }
                        if (dsReport.Tables.Contains("p_report_grouping_subtotal"))
                        {
                            dt = dsReport.Tables["p_report_grouping_subtotal"];
                            validateSelGroupingHdrSub(ref dt, "tot", "subtotal");
                            for (int k = 0; k < dt.Rows.Count; k++)
                            {
                                foreach (DataRow drr in dt.Select("group_sequence=" + dt.Rows[k]["group_sequence"].ToString()))
                                {
                                    DropDownList ddl = (DropDownList)this.Master.FindControl("ContentPlaceHolder3").FindControl("wz_report").FindControl("PlaceHolder_group").FindControl("ddl_tot_field" + drr["field_sequence"].ToString() + "_" + drr["group_sequence"].ToString());
                                    if (ddl != null)
                                    {
                                        if (drr["subtotal_field"].ToString().IndexOf("].[") == -1)
                                            ddl.Text = "[" + objectId + "].[" + drr["subtotal_field"].ToString() + "]";
                                        else
                                            ddl.Text = drr["subtotal_field"].ToString();
                                    }
                                }
                            }
                        }

                        #region commented for phase-1
                        //if (dsReport.Tables.Contains("step3_report_grouping_sort_details"))
                        //{
                        //    dt = dsReport.Tables["step3_report_grouping_sort_details"];
                        //    for (int k = 0; k < dt.Rows.Count; k++)
                        //    {
                        //        DataRow dr = dt.Rows[k];
                        //        if (dr["sort_detail_field"].ToString().IndexOf("].[") != -1)
                        //            ddl_sort_details.Text = dr["sort_detail_field"].ToString();
                        //        else
                        //            ddl_sort_details.Text = "[" + objectId + "].[" + dr["sort_detail_field"].ToString() + "]";
                        //        ddl_sort_order.Text = dr["sort_detail_order"].ToString();
                        //    }
                        //}
                        #endregion

                        for (int j = 1; j <= 3; j++)
                        {
                            if (j == 1)
                                populateNumericFields(ref ddl_grtot_field1, objectId);
                            else if (j == 2)
                                populateNumericFields(ref ddl_grtot_field2, objectId);
                            else if (j == 3)
                                populateNumericFields(ref ddl_grtot_field3, objectId);
                        }
                        if (dsReport.Tables.Contains("p_report_grouping_grand_total"))
                        {
                            dt = dsReport.Tables["p_report_grouping_grand_total"];
                            validateSelGrandTotal(ref dt);
                            for (int k = 0; k < dt.Rows.Count; k++)
                            {
                                DataRow dr = dt.Rows[k];
                                if (dr["attribute_sequence"].ToString() == "1")
                                {
                                    if (dr["grand_total_field"].ToString().IndexOf("].[") == -1)
                                        ddl_grtot_field1.Text = "[" + objectId + "].[" + dr["grand_total_field"].ToString() + "]";
                                    else
                                        ddl_grtot_field1.Text = dr["grand_total_field"].ToString();
                                }
                                else if (dr["attribute_sequence"].ToString() == "2")
                                {
                                    if (dr["grand_total_field"].ToString().IndexOf("].[") == -1)
                                        ddl_grtot_field2.Text = "[" + objectId + "].[" + dr["grand_total_field"].ToString() + "]";
                                    else
                                        ddl_grtot_field2.Text = dr["grand_total_field"].ToString();
                                }
                                else if (dr["attribute_sequence"].ToString() == "3")
                                {
                                    if (dr["grand_total_field"].ToString().IndexOf("].[") == -1)
                                        ddl_grtot_field3.Text = "[" + objectId + "].[" + dr["grand_total_field"].ToString() + "]";
                                    else
                                        ddl_grtot_field3.Text = dr["grand_total_field"].ToString();
                                }
                            }
                        }
                    }
                    break;
                #endregion

                case 4:
                    if (dsReport.Tables.Contains("p_report_header_footer"))
                    {
                        dt = dsReport.Tables["p_report_header_footer"];
                        for (int k = 0; k < dt.Rows.Count; k++)
                        {
                            DataRow dr = dt.Rows[k];
                            txtRepTitle.Text = dr["rpt_title"].ToString();
                            txtHeaderText.Text = dr["rpt_head_text"].ToString();
                            txtFooterText.Text = dr["rpt_foot_text"].ToString();
                            chkDisplayLogo.Checked = Convert.ToBoolean(dr["rpt_logo"].ToString());
                            chkDisplayDate.Checked = Convert.ToBoolean(dr["rpt_date"].ToString());
                            chkDisplayPageNum.Checked = Convert.ToBoolean(dr["rpt_page_no"].ToString());
                            dr = null;
                        }
                    }
                    break;
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("substitute_step_values : Error : " + ex.Message);
        }
        finally
        {
            dt.Dispose();
        }
    }

    private DataSet collect_step_values(int stepIdx)
    {
        DataTable dt = new DataTable();
        try
        {
            dsReport = (DataSet)Session["report_ds"];
            if (dsReport == null)
                dsReport = new DataSet();
            DataRow[] drF = null;
            switch (stepIdx)
            {
                #region Step 1
                case 0:
                case 5:
                    {
                        if (!dsReport.Tables.Contains("p_sy_report"))
                            createDataTable(0, ref dsReport);

                        dt = dsReport.Tables["p_sy_report"];
                        bool isDone = false;
                        if (dt.Rows.Count > 0)
                        {
                            DataRow dr = dt.Rows[0];
                            dr["rpt_base_object"] = lblReportSrc.Text;
                            //dr["rpt_src_id"] = cmbObjects.SelectedValue.Substring(cmbObjects.SelectedValue.IndexOf("@") + 1);
                            dr["rpt_name"] = txtRepName.Text;
                            dr["rpt_desc"] = txtReportDesc.Text;
                            dr["report_category"] = txtReportCategory.Text; // Added by 'Imran Gani' on 28-May-2012, for report category.
                            isDone = true;
                        }
                        if (!isDone)
                        {
                            dt.Rows.Clear();
                            DataRow dr = dt.NewRow();
                            dr["af_row_id"] = "";
                            dr["rpt_base_object"] = lblReportSrc.Text;
                            //dr["rpt_src_id"] = cmbObjects.SelectedValue.Substring(cmbObjects.SelectedValue.IndexOf("@") + 1);
                            dr["rpt_name"] = txtRepName.Text;
                            dr["rpt_desc"] = txtReportDesc.Text;
                            dr["report_category"] = txtReportCategory.Text; // Added by 'Imran Gani' on 28-May-2012, for report category.
                            dt.Rows.Add(dr);
                        }
                    }
                    break;
                #endregion

                #region Step 2
                case 1:
                    {
                        if (!dsReport.Tables.Contains("p_sy_report_att"))
                            createDataTable(1, ref dsReport);

                        dt = dsReport.Tables["p_sy_report_att"];
                        if (IsEdit) 
                            validateSelFields(ref dt);
                        if (!IsEdit)
                        {
                            for (int k = 0; k < lstSelectedFields1.Items.Count; k++)
                            {
                                ListItem li = lstSelectedFields1.Items[k];
                                Label lbl = (Label)this.Master.FindControl("ContentPlaceHolder3").FindControl("wz_report").FindControl("lbl_caption_" + li.Value);

                                TextBox txtBox = (TextBox)this.Master.FindControl("ContentPlaceHolder3").FindControl("wz_report").FindControl("txt_" + li.Value);

                                DropDownList dd1 = (DropDownList)this.Master.FindControl("ContentPlaceHolder3").FindControl("wz_report").FindControl("dd_" + li.Value + "_bold");

                                DropDownList dd2 = (DropDownList)this.Master.FindControl("ContentPlaceHolder3").FindControl("wz_report").FindControl("dd_" + li.Value + "_wwrap");

                                drF = dt.Select("attrib_id='" + li.Value + "'");
                                if (drF.Length > 0)
                                {
                                    //drF[0]["rpt_src_id"] = cmbObjects.SelectedValue.Substring(cmbObjects.SelectedValue.IndexOf("@") + 1);
                                    drF[0]["attrib_id"] = li.Value;
                                    drF[0]["caption"] = txtBox.Text;
                                    drF[0]["is_bold"] = dd1.Text.ToLower() == "yes" ? "true" : "false";
                                    drF[0]["is_wrap"] = dd2.Text.ToLower() == "yes" ? "true" : "false";
                                }
                                else
                                {
                                    DataRow dr = dt.NewRow();
                                    dr["af_row_id"] = "";
                                    //dr["rpt_src_id"] = cmbObjects.SelectedValue.Substring(cmbObjects.SelectedValue.IndexOf("@") + 1);
                                    dr["attrib_id"] = li.Value;
                                    dr["caption"] = txtBox.Text;
                                    dr["is_bold"] = dd1.Text.ToLower() == "yes" ? "true" : "false";
                                    dr["is_wrap"] = dd2.Text.ToLower() == "yes" ? "true" : "false";
                                    dt.Rows.Add(dr);
                                }
                            }
                        }
                    }
                    break;
                #endregion

                #region Step 3
                case 2: // Added by Imran Gani on 20-Jul-2012, for Source Filter.
                    if (!dsReport.Tables.Contains("p_report_source_filter"))
                        createDataTable(2, ref dsReport);
                    dt = dsReport.Tables["p_report_source_filter"];
                    //if (hfFilterTable != null && hfFilterTable.Value != "")
                    getSourceFilter(dt);
                    dsReport.Tables["p_sy_report"].Rows[0]["source_filter_grouping"] = hfFilterGroup.Value;
                    break;
                #endregion

                #region Step 4
                case 3:
                    {
                        if (!dsReport.Tables.Contains("p_report_grouping"))
                            createDataTable(3, ref dsReport);

                        dt = dsReport.Tables["p_report_grouping"];
                        validateSelGrouping(ref dt, IsEdit);
                            
                        int grpCnt = Convert.ToInt32(hiddenGroupCnt.Value);
                        for (int k = 1; k <= grpCnt; k++)
                        {
                            DropDownList ddl = (DropDownList)this.Master.FindControl("ContentPlaceHolder3").FindControl("wz_report").FindControl("PlaceHolder_group").FindControl("ddl_group_field_" + k.ToString());
                            if (convertText(ddl.SelectedValue) == "") continue;

                            DropDownList dd2 = (DropDownList)this.Master.FindControl("ContentPlaceHolder3").FindControl("wz_report").FindControl("PlaceHolder_group").FindControl("ddl_group_order_" + k.ToString());

                            CheckBox cb1 = (CheckBox)this.Master.FindControl("ContentPlaceHolder3").FindControl("wz_report").FindControl("PlaceHolder_group").FindControl("cb_showhdr_" + k.ToString());

                            CheckBox cb2 = (CheckBox)this.Master.FindControl("ContentPlaceHolder3").FindControl("wz_report").FindControl("PlaceHolder_group").FindControl("cb_showsub_" + k.ToString());

                            if (dt.Rows.Count > 0)
                            {
                                if (dt.Rows.Count >= k)
                                {
                                    if (dt.Rows[k - 1]["af_row_id"].ToString().Trim() != "")
                                    {
                                        drF = dt.Select("attribute_sequence=" + k.ToString() + " and af_row_id='" + dt.Rows[k - 1]["af_row_id"].ToString() + "'"); // + convertText(ddl.SelectedValue) + "'");
                                        if (drF.Length > 0)
                                        {
                                            drF[0]["attribute_sequence"] = k;
                                            drF[0]["grouping_field"] = convertText(ddl.SelectedValue);
                                            drF[0]["grouping_order"] = convertText(dd2.SelectedItem.Text);
                                            drF[0]["show_header"] = cb1.Checked.ToString();
                                            drF[0]["show_subtotal"] = cb2.Checked.ToString();
                                        }
                                        else
                                        {
                                            if (convertText(ddl.SelectedValue) == "")
                                                continue;
                                            DataRow dr = dt.NewRow();
                                            dr["af_row_id"] = "";
                                            dr["attribute_sequence"] = k;
                                            dr["grouping_field"] = convertText(ddl.SelectedValue);
                                            dr["grouping_order"] = convertText(dd2.SelectedItem.Text);
                                            dr["show_header"] = cb1.Checked.ToString();
                                            dr["show_subtotal"] = cb2.Checked.ToString();
                                            dt.Rows.Add(dr);
                                        }
                                    }
                                    else
                                    { 
                                        drF = dt.Select("attribute_sequence=" + k.ToString());
                                        if (drF.Length > 0)
                                        {
                                            drF[0]["attribute_sequence"] = k;
                                            drF[0]["grouping_field"] = convertText(ddl.SelectedValue);
                                            drF[0]["grouping_order"] = convertText(dd2.SelectedItem.Text);
                                            drF[0]["show_header"] = cb1.Checked.ToString();
                                            drF[0]["show_subtotal"] = cb2.Checked.ToString();
                                        }
                                    }
                                }
                                else
                                {
                                    if (convertText(ddl.SelectedValue) == "")
                                        continue;
                                    DataRow dr = dt.NewRow();
                                    dr["af_row_id"] = "";
                                    dr["attribute_sequence"] = k;
                                    dr["grouping_field"] = convertText(ddl.SelectedValue);
                                    dr["grouping_order"] = convertText(dd2.SelectedItem.Text);
                                    dr["show_header"] = cb1.Checked.ToString();
                                    dr["show_subtotal"] = cb2.Checked.ToString();
                                    dt.Rows.Add(dr);
                                }
                            }
                            else //if (dt.Rows.Count == 0)
                            {
                                if (convertText(ddl.SelectedValue) == "")
                                    continue;
                                DataRow dr = dt.NewRow();
                                dr["af_row_id"] = "";
                                dr["attribute_sequence"] = k;
                                dr["grouping_field"] = convertText(ddl.SelectedValue);
                                dr["grouping_order"] = convertText(dd2.SelectedItem.Text);
                                dr["show_header"] = cb1.Checked.ToString();
                                dr["show_subtotal"] = cb2.Checked.ToString();
                                dt.Rows.Add(dr);
                            }
                        }
                        //Header table
                        dt = dsReport.Tables["p_report_grouping_header"];
                        //if (IsEdit) 
                        validateSelGroupingHdrSub(ref dt, "hdr", "header");
                        //dt.Rows.Clear();

                        Hashtable hsNewVal = new Hashtable();
                        for (int groupIdx = 1; groupIdx <= grpCnt; groupIdx++)
                        {
                            for (int fieldIdx = 1; fieldIdx <= 3; fieldIdx++)
                            {
                                DropDownList ddl = (DropDownList)this.Master.FindControl("ContentPlaceHolder3").FindControl("wz_report").FindControl("PlaceHolder_group").FindControl("ddl_hdr_field" + fieldIdx.ToString() + "_" + groupIdx.ToString());
                                if (ddl != null)
                                {
                                    if (convertText(ddl.SelectedValue) == "")
                                        continue;
                                    drF = dt.Select("group_sequence=" + groupIdx.ToString() + " and field_sequence=" + fieldIdx.ToString());
                                    if (drF.Length > 0)
                                    {
                                        drF[0]["header_field"] = convertText(ddl.SelectedValue);
                                        drF[0]["group_sequence"] = groupIdx;
                                        drF[0]["field_sequence"] = fieldIdx;                                        
                                    }
                                    else
                                    {
                                        if (convertText(ddl.SelectedValue).Trim() == "") continue;
                                        hsNewVal.Add(groupIdx.ToString() + ":" + fieldIdx.ToString(), convertText(ddl.SelectedValue));
                                    }
                                }

                            }
                            foreach (string key in hsNewVal.Keys)
                            {
                                DataRow dr = dt.NewRow();
                                dr["af_row_id"] = "";
                                dr["rpt_group_id"] = key.Substring(0, key.IndexOf(":"));
                                dr["header_field"] = hsNewVal[key];
                                dr["group_sequence"] = key.Substring(0, key.IndexOf(":"));
                                dr["field_sequence"] = key.Substring(key.IndexOf(":")+1);
                                dt.Rows.Add(dr);
                            }
                            hsNewVal.Clear();
                        }

                        //subtotal table
                        dt = dsReport.Tables["p_report_grouping_subtotal"];
                        //if (IsEdit) 
                            validateSelGroupingHdrSub(ref dt, "tot", "subtotal");
                        hsNewVal.Clear();   
                        for (int groupIdx = 1; groupIdx <= grpCnt; groupIdx++)
                        {
                            for (int fieldIdx = 1; fieldIdx <= 3; fieldIdx++)
                            {
                                DropDownList ddl = (DropDownList)this.Master.FindControl("ContentPlaceHolder3").FindControl("wz_report").FindControl("PlaceHolder_group").FindControl("ddl_tot_field" + fieldIdx.ToString() + "_" + groupIdx.ToString());
                                if (ddl != null)
                                {
                                    if (convertText(ddl.SelectedValue) == "")
                                        continue;
                                    drF = dt.Select("group_sequence=" + groupIdx.ToString() + " and field_sequence=" + fieldIdx.ToString()); //subtotal_field='" + convertText(ddl.SelectedValue) + "' and 
                                    if (drF.Length > 0)
                                    {
                                        drF[0]["subtotal_field"] = convertText(ddl.SelectedValue);
                                        drF[0]["group_sequence"] = groupIdx;
                                        drF[0]["field_sequence"] = fieldIdx;
                                    }
                                    else
                                    {
                                        if (convertText(ddl.SelectedValue).Trim() == "") continue;
                                        hsNewVal.Add(groupIdx.ToString() + ":" + fieldIdx.ToString(), convertText(ddl.SelectedValue));
                                    }
                                }

                            }
                            foreach (string key in hsNewVal.Keys)
                            {
                                DataRow dr = dt.NewRow();
                                dr["af_row_id"] = "";
                                dr["rpt_group_id"] = key.Substring(0, key.IndexOf(":"));
                                dr["subtotal_field"] = hsNewVal[key];
                                dr["group_sequence"] = key.Substring(0, key.IndexOf(":"));
                                dr["field_sequence"] = key.Substring(key.IndexOf(":") + 1);
                                dt.Rows.Add(dr);
                            }
                            hsNewVal.Clear();
                        }

                        #region commented for phase-1
                        //sort details
                        //dt = dsReport.Tables["step3_report_grouping_sort_details"];
                        //drF = dt.Select("sort_detail_field='" + convertText(ddl_sort_details.SelectedValue) + "'");
                        //if (drF.Length > 0)
                        //{
                        //    drF[0]["sort_detail_field"] = convertText(ddl_sort_details.SelectedValue);
                        //    drF[0]["sort_detail_order"] = ddl_sort_order.SelectedItem.Text;
                        //}
                        //else
                        //{
                        //    string tmp = convertText(ddl_sort_details.SelectedValue);
                        //    if (tmp.Trim() != "")
                        //    {
                        //        DataRow dr = dt.NewRow();
                        //        dr["af_row_id"] = "";
                        //        dr["sort_detail_field"] = tmp;
                        //        dr["sort_detail_order"] = ddl_sort_order.SelectedItem.Text;
                        //        dt.Rows.Add(dr);
                        //    }
                        //}
                        //dt = null;
                        #endregion

                        //grand total
                        dt = dsReport.Tables["p_report_grouping_grand_total"];
                        validateSelGrandTotal(ref dt);
                        //dt.Rows.Clear();
                        for (int j = 1; j <= 3; j++)
                        {
                            string tmp = "";
                            if (j==1)
                                tmp = convertText(ddl_grtot_field1.SelectedValue);
                            else if (j==2)
                                tmp = convertText(ddl_grtot_field2.SelectedValue);
                            else if (j==3)
                                tmp = convertText(ddl_grtot_field3.SelectedValue);
                            if (tmp.Trim() == "") continue;

                            drF = dt.Select("attribute_sequence=" + j.ToString());//grand_total_field='" + tmp + "' and 
                            if (drF.Length > 0)
                            {
                                drF[0]["grand_total_field"] = tmp;
                                drF[0]["attribute_sequence"] = j.ToString();
                            }
                            else
                            {
                                DataRow dr = dt.NewRow();
                                dr["af_row_id"] = "";
                                dr["grand_total_field"] = tmp;
                                dr["attribute_sequence"] = j.ToString();
                                dt.Rows.Add(dr);
                            }
                        }
                    }
                    break;
                #endregion

                case 4:
                    if (!dsReport.Tables.Contains("p_report_header_footer"))
                        createDataTable(4, ref dsReport);

                    dt = dsReport.Tables["p_report_header_footer"];
                    if (dt.Rows.Count > 0)
                    {
                        DataRow dr = dt.Rows[0];
                        dr["rpt_id"] = hf_af_row_id1.Value;
                        dr["rpt_title"] = txtRepTitle.Text;
                        dr["rpt_head_text"] = txtHeaderText.Text;
                        dr["rpt_foot_text"] = txtFooterText.Text;
                        dr["rpt_logo"] = chkDisplayLogo.Checked.ToString();
                        dr["rpt_date"] = chkDisplayDate.Checked.ToString();
                        dr["rpt_page_no"] = chkDisplayPageNum.Checked.ToString();
                    }
                    else
                    {
                        DataRow dr = dt.NewRow();
                        dr["af_row_id"] = "";
                        dr["rpt_id"] = hf_af_row_id1.Value;
                        dr["rpt_title"] = txtRepTitle.Text;
                        dr["rpt_head_text"] = txtHeaderText.Text;
                        dr["rpt_foot_text"] = txtFooterText.Text;
                        dr["rpt_logo"] = chkDisplayLogo.Checked.ToString();
                        dr["rpt_date"] = chkDisplayDate.Checked.ToString();
                        dr["rpt_page_no"] = chkDisplayPageNum.Checked.ToString();
                        dt.Rows.Add(dr);
                    }
                    break;
            }

            Session["report_ds"] = dsReport;
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("collect_step_values : Error : " + ex.Message);
        }
        finally
        {
            dt.Dispose();
        }
        return dsReport;
    }

    protected void wz_Report_NextButtonClick(object sender, WizardNavigationEventArgs e)
    {
        try
        {            
            ImageButton newWindow = (ImageButton)this.wz_Report.FindControl("HeaderContainer$imgNewWindow1");
            newWindow.Visible = false;
            collect_step_values(wz_Report.ActiveStepIndex);
            substitute_step_values(e.NextStepIndex);
            if (txtRepName.Text == "")
            {
                if (txtRepTitle.Text.Trim() != "")
                    txtRepName.Text = txtRepTitle.Text;
                else
                    txtRepName.Text = cmbObjects.SelectedItem.Text;
            }
            if (wz_Report.ActiveStepIndex == 5)
                generateReport(false, "");
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("wz_Report_NextButtonClick : Error : " + ex.Message);
        }
    }

    protected void wz_Report_PreviousButtonClick(object sender, WizardNavigationEventArgs e)
    {
        try
        {
            ImageButton newWindow = (ImageButton)this.wz_Report.FindControl("HeaderContainer$imgNewWindow1");
            newWindow.Visible = false;
            collect_step_values(e.CurrentStepIndex);
            substitute_step_values(e.NextStepIndex);
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("wz_Report_PreviousButtonClick : Error : " + ex.Message);
        }
    }

    protected void wz_Report_CancelButtonClick(object sender, EventArgs e)
    {
        try
        {
            HDDatabase HDD = new HDDatabase();
            dsReport = null;
            dsPageInfo = null;

            Session["report_ds"] = null;
            Session["FieldProperties"] = null;
            Session["param"] = null;
            hiddenTmp.Value = "";
            hiddenGroupCnt.Value = "";
            hiddenParam.Value = "";
            Response.Redirect("DisplayGrid.aspx?mn=" + HDD.GetColumnValue("sy_mnu", "af_row_id", "pageset_id = '6421de320e189de8' and pageset_url = 'reportwizard_new.aspx'") + "&pgs_id=6421de320e189de8", false); // pageset_id and pgs_id=ps_report
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("wz_Report_CancelButtonClick : Error : " + ex.Message);
        }
    }

    private bool validateCaptions()
    {
        bool retFlag = true;
        try
        {
            string tmpStr = "";
            for (int k = 0; k < lstSelectedFields1.Items.Count; k++)
            {
                ListItem li = lstSelectedFields1.Items[k];
                TextBox txtBox = (TextBox)this.Master.FindControl("ContentPlaceHolder3").FindControl("wz_report").FindControl("txt_" + li.Value);
                if (tmpStr.ToLower().Trim() == txtBox.Text.Trim().ToLower())
                {
                    retFlag = false;
                    break;
                }
                else
                    tmpStr = txtBox.Text;
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("validateCaptions : Error : " + ex.Message);
        }
        return retFlag;
    }

    protected void wz_Report_ActiveStepChanged(object sender, EventArgs e)
    {
        try
        {
            switch (wz_Report.ActiveStepIndex)
            {
                case 0:
                    break;
                case 1:
                    ImageButton newWindow = (ImageButton)this.wz_Report.FindControl("HeaderContainer$imgNewWindow1");
                    newWindow.Visible = false;
                    break;
                case 2: // Added by Imran Gani on 20-Jul-2012, for Source Filter.
                    if (dsReport.Tables["p_sy_report"].Rows[0]["rpt_base_object"].ToString() == "SQL")
                        wz_Report.ActiveStepIndex = 3;
                    break;
                case 3: 
                    //if (!validateCaptions())
                    //{
                    //    wz_Report.ActiveStepIndex = 1;
                    //    lblMessage.Text = "Captions are same. Please modify the captions";
                    //    return;
                    //}
                    if (Convert.ToInt32(hiddenGroupCnt.Value) == 3)
                    {
                        btnAddGrouping.Enabled = false;
                        return;
                    }
                    else
                        btnAddGrouping.Enabled = true;

                    if (!IsEdit)
                    {
                        //populateFieldsFromSelectedList(ref ddl_sort_details); //commented for phase-1
                        if (lblMsgStep2.Text.Trim() != string.Empty && lblMsgStep2.Text.Contains("$"))
                        {
                            if (ddl_grtot_field1.Items.Count <= 1)
                                populateNumericFields(ref ddl_grtot_field1, lblMsgStep2.Text.Substring(lblMsgStep2.Text.IndexOf("$") + 1));
                            if (ddl_grtot_field2.Items.Count <= 1)
                                populateNumericFields(ref ddl_grtot_field2, lblMsgStep2.Text.Substring(lblMsgStep2.Text.IndexOf("$") + 1));
                            if (ddl_grtot_field3.Items.Count <= 1)
                                populateNumericFields(ref ddl_grtot_field3, lblMsgStep2.Text.Substring(lblMsgStep2.Text.IndexOf("$") + 1));
                        }
                    }
                    //populateFields(lblMsgStep2.Text.Substring(lblMsgStep2.Text.IndexOf("$") + 1), ref ddl_grtot_field3, true);
                    newWindow = (ImageButton)this.wz_Report.FindControl("HeaderContainer$imgNewWindow1");
                    newWindow.Visible = false;
                    break;
                case 4:
                    if (!validateGrouping())
                    {
                        wz_Report.ActiveStepIndex = 3; 
                        substitute_step_values(3);
                        return;
                    }
                    break;
                case 5:
                    if (txtRepName.Text == "")
                    {
                        if (txtRepTitle.Text.Trim() != "")
                            txtRepName.Text = txtRepTitle.Text;
                        else
                            txtRepName.Text = cmbObjects.SelectedItem.Text;
                    }
                    break;
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("wz_Report_ActiveStepChanged : Error : " + ex.Message);
        }
    }

    private bool validateGrouping()
    {
        try 
        {
            DataSet tmpDS = (DataSet)Session["report_ds"];
            if (tmpDS == null) return true;

            if (!tmpDS.Tables.Contains("step3_report_grouping")) return true;

            foreach (DataRow dr in tmpDS.Tables["step3_report_grouping"].Rows)
            {
                if (tmpDS.Tables["step3_report_grouping"].Select("grouping_field='" + dr["grouping_field"].ToString() + "'").Length > 1)
                {
                    lblGroupMsg.Text = "Please choose different grouping fields for each grouping.";
                    return false;
                }
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("validateGrouping : Error : " + ex.Message);
        }
        return true;
    }

    private void populateFieldsFromSelectedList(ref DropDownList ddList)
    {
        try
        {
            ddList.Items.Clear();
            ddList.Items.Add(new ListItem("---None---", ""));

            for (int k = 0; k < lstSelectedFields1.Items.Count; k++)
            {
                ListItem li = lstSelectedFields1.Items[k];
                TextBox txtBox = (TextBox)this.Master.FindControl("ContentPlaceHolder3").FindControl("wz_report").FindControl("txt_" + li.Value);
                string sAttributeName = "";
                if (txtBox != null)
                    sAttributeName = txtBox.Text;
                else
                    sAttributeName = li.Text.Substring(li.Text.IndexOf("].[") + 3, li.Text.Length - 1 - (li.Text.IndexOf("].[") + 3));
                ddList.Items.Add(new ListItem(sAttributeName, li.Value));
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("populateFieldsFromSelectedList : Error : " + ex.Message);
        }
    }

    private void populateNumericFields(ref DropDownList ddList, string objName)
    {
        try
        {
            ddList.Items.Clear();
            ddList.Items.Add(new ListItem("---None---", ""));

            DataTable dt = null;
            if (cmbObjects.SelectedValue.StartsWith("SQL@"))
            {
                dt = hdd.GetDataTable("select report_base_id, report_base_name,report_base_sql from sy_report_sql where report_base_id='" + objName + "'");
                if (dt == null) return;
                if (dt.Rows.Count == 0) return;
                DataTable tmpDT = hdd.GetDataTable(dt.Rows[0]["report_base_sql"].ToString());
                for (int k = 0; k < lstSelectedFields1.Items.Count; k++)
                {
                    ListItem li = lstSelectedFields1.Items[k];
                    TextBox txtBox = (TextBox)this.Master.FindControl("ContentPlaceHolder3").FindControl("wz_report").FindControl("txt_" + li.Value);
                    string sAttributeName = li.Text.Substring(li.Text.IndexOf("].[") + 3, li.Text.Length - 1 - (li.Text.IndexOf("].[") + 3));
                    if (!tmpDT.Columns.Contains(sAttributeName)) continue;
                    if (tmpDT.Columns[sAttributeName].DataType.Name.ToLower().StartsWith("int") || tmpDT.Columns[sAttributeName].DataType.Name.ToLower().StartsWith("deci") || tmpDT.Columns[sAttributeName].DataType.Name.ToLower().StartsWith("float") || tmpDT.Columns[sAttributeName].DataType.Name.ToLower().StartsWith("doub"))
                    {
                        if (txtBox != null)
                            ddList.Items.Add(new ListItem(txtBox.Text, li.Value));
                        else
                            ddList.Items.Add(new ListItem(sAttributeName, li.Value));
                    }
                }
            }
            else if (cmbObjects.SelectedValue.StartsWith("OBJECT@"))
            {
                dt = hdd.GetDataTable("select control_name,control_attrib_id,control_attrib_type from sy_pg_ctr where control_attrib_type in ('DC','NU','CU') and page_id=(select af_row_id from sy_pg where object_id='" + objName + "')");
                if (dt == null) return;
                if (dt.Rows.Count == 0) return;
                for (int k = 0; k < lstSelectedFields1.Items.Count; k++)
                {
                    ListItem li = lstSelectedFields1.Items[k];
                    TextBox txtBox = (TextBox)this.Master.FindControl("ContentPlaceHolder3").FindControl("wz_report").FindControl("txt_" + li.Value);
                    string sAttributeName = sAttributeName = li.Text.Substring(li.Text.IndexOf("].[") + 3, li.Text.Length - 1 - (li.Text.IndexOf("].[") + 3));
                    DataRow[] drF = dt.Select("control_name='" + sAttributeName + "'");
                    if (drF != null)
                    {
                        if (drF.Length > 0)
                        {
                            if (txtBox != null)
                                ddList.Items.Add(new ListItem(txtBox.Text, li.Value));
                            else
                                ddList.Items.Add(new ListItem(sAttributeName, li.Value));
                        }
                    }
                }
            }
            dt = null;
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("populateNumericFields : Error : " + ex.Message);
        }
    }

    protected void cmbObject_SelectedIndexChanged(object sender, EventArgs e)
    {
        try
        {
            if (cmbObjects.SelectedIndex == -1) return;

            if (cmbObjects.SelectedValue.Trim() == "")
            {
                lstFields1.Items.Clear();
                lstSelectedFields1.Items.Clear();
                return;
            }

            lblFieldsMsg1.Text = "";

            if (dsReport != null)
            {
                if (dsReport.Tables.Contains("p_sy_report_att"))
                {
                    if (dsReport.Tables["p_sy_report_att"].Rows.Count > 0)
                    {
                        if (dsReport.Tables["p_sy_report_att"].Rows[0]["attrib_id"].ToString().IndexOf("].[")> 0)
                        {
                            string objId = dsReport.Tables["p_sy_report_att"].Rows[0]["attrib_id"].ToString().Substring(1, dsReport.Tables["p_sy_report_att"].Rows[0]["attrib_id"].ToString().IndexOf("].[")).TrimEnd(']');
                            if (objId.Trim().ToLower() != cmbObjects.SelectedValue.Substring(cmbObjects.SelectedValue.IndexOf("@") + 1).Trim().ToLower())
                            {
                                if (!IsEdit)
                                {
                                    dsReport.Tables.Clear();
                                    Session["FieldProperties"] = null;
                                    Session["param"] = null;
                                    hiddenTmp.Value = "";
                                    hiddenGroupCnt.Value = "";
                                }
                            }
                        }
                    }
                }
            }


            //string sSql = "Select object_id from sy_obj where object_id='" + cmbObjects.SelectedValue + "'";
            //dtObj = hdd.GetDataTable(sSql);

            if (cmbObjects.SelectedValue.ToUpper().StartsWith("SQL@"))
            {
                populateFieldsFromQuery(lstFields1,null);
                lblReportSrc.Text = "SQL";
            }
            else if (cmbObjects.SelectedValue.ToUpper().StartsWith("OBJECT@"))
            {
                populateListBox(lstFields1,null);
                lblReportSrc.Text = "Object";
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("cmbObject_SelectedIndexChanged : Error : " + ex.Message);
        }
    }

    private void loadObjectsinCombo(string Sql)
    {
        try
        {
            Sql = applysecurity(Sql);
            dtObj = hdd.GetDataTable(Sql);
            AddDefaultObjects(ref dtObj); //Added by Srivatsan
            lblGroupMsg.Text = "";
            //lblDesc1.Text = "";
            lstFields1.Items.Clear();
            lstSelectedFields1.Items.Clear();
            cmbObjects.Items.Clear();
            cmbObjects.Items.Add(new ListItem("--Select a Table/Query--", ""));
            cmbObjects.Items.Add(new ListItem("--Tables--", ""));
            //Adding Tables
            foreach (DataRow dr in dtObj.Select("","object_name asc"))
            {
                if (hdds.getObjectRightsForUser(dr["object_id"].ToString(), "read"))
                {
                    ListItem liObject = new ListItem(dr["object_name"].ToString(), "OBJECT@" + dr["object_id"].ToString());
                    cmbObjects.Items.Add(liObject);
                }
            }
            cmbObjects.Items.Add(new ListItem("--Queries--", ""));
            //Adding Queries
            ArrayList alList = new ArrayList();
            //Sql = applysecurity("select * from sy_report_sql");
            Sql = "Select * from sy_report_sql";
            dtObj = hdd.GetDataTable(Sql);
            foreach (DataRow dr in dtObj.Select())
            {
                ListItem liObject = new ListItem(dr["report_base_name"].ToString(), "SQL@" + dr["report_base_id"].ToString());
                if (dr["report_base_param"].ToString().ToUpper().StartsWith("PARAMETERS") || dr["report_base_sql"].ToString().Contains("$") || dr["report_base_sql"].ToString().Contains("#"))
                    alList.Add(liObject);
                else
                    cmbObjects.Items.Add(liObject);
            }
            cmbObjects.Items.Add(new ListItem("--Parameter Queries--", ""));
            foreach(ListItem li in alList)
                cmbObjects.Items.Add(li);
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("loadObjectsinCombo : Error : " + ex.Message);
        }
    }

    private string getSQLQuery(string sSql, bool isParam, string param)
    {
        string retQry = sSql;
        try        
        {
            Hashtable hsParam = new Hashtable();
            if (!isParam)
            {
                getParameters("$", ref hsParam, sSql);
                getParameters("#", ref hsParam, sSql);
                foreach (string sParam in hsParam.Keys)
                    retQry = retQry.Replace(sParam, "0");
            }
            else
            {
                //get the variables list from p_sy_report_sql_report_base_param
                if (param.Trim().ToLower().StartsWith("parameters"))
                    param = param.Substring("parameters".Length + 1).Trim();
                foreach (string str1 in param.Split(','))
                {
                    if (str1.Trim() == "") continue;
                    if (str1.IndexOf("=") == -1)
                        hsParam.Add(str1.Trim(), getDefaultValue(str1.Substring(str1.IndexOf("]") + 1).Trim()));
                    else
                        hsParam.Add(str1.Substring(0, str1.IndexOf("=")).Trim(), str1.Substring(str1.IndexOf("=") + 1).Trim());
                }
                foreach (string sParam in hsParam.Keys)
                {
                    string tmp = "$" + sParam.Substring(0, sParam.LastIndexOf("[")).Replace("[", "").Replace("]", "") + "$";
                    //retQry = retQry.Replace(tmp, hsParam[sParam].ToString());
                    retQry = retQry.Replace(tmp, hsParam[sParam].ToString().TrimStart('\'').TrimEnd('\'').Replace("''", "'")); // Added by 'Imran Gani' on 29-Oct-12, to encode the input value.
                }
                    
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("getSQLQuery : Error : " + ex.Message);
        }
        return retQry;
    }

    private string getDefaultValue(string object_field_id)
    {
        string retValue = "''";
        try
        {
            string object_table = object_field_id.Replace("[", "").Substring(0, object_field_id.Replace("[", "").IndexOf("."));
            string field_id = object_field_id.Substring(object_field_id.IndexOf(".") + 1).Replace("]", "");

            HDDatabase hdd = new HDDatabase();
            DataTable dt = hdd.GetDataTable("select control_attrib_type from sy_pg_ctr where control_id='" + field_id + "' and page_id=(select af_row_id from sy_pg where page_table_name='" + object_table + "')");
            if (dt.Rows.Count > 0)
            {
                if (dt.Rows[0]["control_attrib_type"].ToString().ToUpper() == "TX")
                    retValue = "''";
                else if (dt.Rows[0]["control_attrib_type"].ToString().ToUpper() == "DA" || dt.Rows[0]["control_attrib_type"].ToString().ToUpper() == "DT")
                    retValue = "'" + DateTime.Now.ToShortDateString() + "'";
                else if (dt.Rows[0]["control_attrib_type"].ToString().ToUpper() == "BO")
                    retValue = "'false'";
                else
                    retValue = "0";
            }
            dt = null;
            hdd = null;
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("getDefaultValue : Error : " + ex.Message);
        }
        return retValue;
    }

    private void populateFieldsFromQuery(ListBox Fields, string selectAllFlag)
    {
        try
        {
            if (selectAllFlag == "SA")
                lstFields1.Items.Clear();
            else if (selectAllFlag == "DS")
                lstSelectedFields1.Items.Clear();
            else
            {
                lstFields1.Items.Clear();
                lstSelectedFields1.Items.Clear();
            }

            string sQueryId = cmbObjects.SelectedValue.Substring(cmbObjects.SelectedValue.IndexOf("@") + 1);
            hiddenParam.Value = "";
            DataRow dr = hdd.GetTableRow("select * from sy_report_sql where report_base_id=" + sQueryId);
            if (dr != null)
            {
                //decode added by Sampath on 27-Apr-2012
                //CommonFunctions.decodeData(dr);
                string sSql = dr["report_base_param"].ToString() + ";" + dr["report_base_sql"].ToString();
                string sQueryName = cmbObjects.SelectedItem.Text;

                if (sSql.ToLower().StartsWith("parameters"))
                {
                    sSql = getSQLQuery(dr["report_base_sql"].ToString(), true, dr["report_base_param"].ToString());
                    hiddenParam.Value = "P";
                }
                else if (sSql.Contains("$") || sSql.Contains("#"))
                {
                    sSql = getSQLQuery(sSql, false, "");
                    hiddenParam.Value = "P";
                }

                lstFields1.Enabled = true;
                lstSelectedFields1.Enabled = true;
                imgSelect1.Enabled = true;
                imgUnselect1.Enabled = true;
                imgSelectAll1.Enabled = true;
                imgUnselectAll1.Enabled = true;
                imgUp1.Enabled = true;
                imgDown1.Enabled = true;

                DataTable dtQuery = null;
                if (sSql != "")
                {
                    dtQuery = hdd.GetDataTable(sSql);
                    if (dtQuery != null)
                    {
                        foreach (DataColumn dc in dtQuery.Columns)
                        {
                            if (dc.ColumnName.ToString() != "af_row_id") // Added by 'Imran Gani' on 02/05/12, to skip af_row_id field in selection list.
                            {
                                ListItem li = new ListItem("[" + sQueryName + "].[" + dc.ColumnName + "]", "[" + sQueryId + "].[" + dc.ColumnName.Replace(" ", "_") + "]");
                                if (!Fields.Items.Contains(li))
                                    Fields.Items.Add(li);
                            }
                        }
                        imgSelect1.Enabled = true;
                        imgUnselect1.Enabled = false;
                        imgSelectAll1.Enabled = true;
                        imgUnselectAll1.Enabled = false;
                        imgUp1.Enabled = false;
                        imgDown1.Enabled = false;
                    }
                }
                dr = null;
            }
        }

        catch (Exception Ex)
        {
            LogWriter.WriteLog("populateFieldsFromQuery : Error : " + Ex.Message);
        }
    }

    private void loadSQLinCombo()
    {

        string sSql = "Select * from sy_report_sql";

        //sSql = applysecurity(sSql);

        dtObj = hdd.GetDataTable(sSql);
        lblGroupMsg.Text = "";
        //lblDesc1.Text = "";
        lstFields1.Items.Clear();
        lstSelectedFields1.Items.Clear();
        cmbObjects.Items.Clear();
        cmbObjects.Items.Add("--Select a query--");
        foreach (DataRow dr in dtObj.Select())
        {
            ListItem liObject = new ListItem(dr["report_base_name"].ToString(), dr["report_base_id"].ToString());
            cmbObjects.Items.Add(liObject);
        }
    }

    private void populateFields(string ObjectId, ListBox Fields, string selectAllFlag)
    {
        lstFields1.Enabled = true;
        lstSelectedFields1.Enabled = true;
        imgSelect1.Enabled = true;
        imgUnselect1.Enabled = true;
        imgSelectAll1.Enabled = true;
        imgUnselectAll1.Enabled = true;
        imgUp1.Enabled = true;
        imgDown1.Enabled = true;

        if (selectAllFlag=="SA")
            lstFields1.Items.Clear();
        else if (selectAllFlag == "DS")
            lstSelectedFields1.Items.Clear();
        else
        {
            lstFields1.Items.Clear();
            lstSelectedFields1.Items.Clear();
        }

        string sObjectName = cmbObjects.SelectedItem.Text;
        ObjectId = cmbObjects.SelectedValue.Substring(cmbObjects.SelectedValue.IndexOf("@") + 1);
        string sSql = "Select * from sy_obj";
        dtObj = hdd.GetDataTable(sSql);
        DataRow[] drr = dtObj.Select("object_id='" + ObjectId + "'");
        if (drr.Length > 0)
        {
            //sSql = "Select * from sy_obj_mas_detail where object_id = '" + drr[0]["af_row_id"].ToString() + "'";
            sSql = "Select mo.af_row_id,mo.attrib_id,ch.master_obj from sy_obj ob, sy_obj_att mo, sy_obj_mas_detail ch ";
            sSql += "where ob.[object_id]=ch.master_obj and mo.[object_id]=ob.af_row_id and ch.[object_id] = '" + drr[0]["af_row_id"].ToString() + "' ";
            sSql += "and mo.attrib_id=(Select attrib_id from sy_obj_mas_detail where object_id = '" + drr[0]["af_row_id"].ToString() + "')"; 

            DataTable dtFields = hdd.GetDataTable(sSql);            
            foreach (DataRow dr in dtFields.Select())
            {
                ListItem liObject = new ListItem("[" + sObjectName + "].[" + dr["attrib_id"].ToString() + "]", "[" + dr["master_obj"].ToString() + "].[" + dr["af_row_id"].ToString() + "]");
                Fields.Items.Add(liObject);
            }

            sSql = "Select * from sy_obj_att where object_id = '" + drr[0]["af_row_id"].ToString() + "'";

            dtFields = hdd.GetDataTable(sSql);

            foreach (DataRow dr in dtFields.Select())
            {
                string sAttrib_Name = "";
                if (dr["attrib_name"].ToString() == "")
                    sAttrib_Name = dr["attrib_id"].ToString();
                else
                    sAttrib_Name = dr["attrib_name"].ToString();
                if (dr["attrib_id"].ToString() != "af_row_id")
                {
                    ListItem liObject = new ListItem("[" + sObjectName + "].[" + sAttrib_Name + "]", "[" + ObjectId + "].[" + dr["af_row_id"].ToString() + "]");
                    if (!Fields.Items.Contains(liObject))
                        Fields.Items.Add(liObject);
                }
            }
            dtFields.Dispose();
            dtFields = null;
        }
        imgSelect1.Enabled = true;
        imgSelectAll1.Enabled = true;
    }
    
    protected void imgSelect_Click(object sender, ImageClickEventArgs e)
    {
        if (lstFields1.Items.Count > 0)
        {
            lstSelectedFields1.SelectedIndex = -1;

            if (lstFields1.SelectedItem != null) //lstFields.Items[0].Selected = true;
            {
                lblFieldsMsg1.Text = "";
                ListItem liSelected = lstFields1.SelectedItem;
                lstFields1.Items.Remove(liSelected);
                lstSelectedFields1.Items.Add(liSelected);
                imgUnselect1.Enabled = true;
                imgUnselectAll1.Enabled = true;
                imgUp1.Enabled = true;
                imgDown1.Enabled = true;
                if (lstFields1.Items.Count == 0)
                {
                    imgSelect1.Enabled = false;
                    imgSelectAll1.Enabled = false;
                }
            }
        }
    }

    protected void imgUnselect_Click(object sender, ImageClickEventArgs e)
    {
        if (lstSelectedFields1.Items.Count > 0)
        {
            lstFields1.SelectedIndex = -1;
            if (lstSelectedFields1.SelectedItem != null) //lstSelectedFields.Items[0].Selected = true;
            {
                ListItem liSelected = lstSelectedFields1.SelectedItem;
                lstSelectedFields1.Items.Remove(liSelected);
                lstFields1.Items.Add(liSelected);
                imgSelect1.Enabled = true;
                imgSelectAll1.Enabled = true;
                if (lstSelectedFields1.Items.Count == 0)
                {
                    imgUnselect1.Enabled = false;
                    imgUnselectAll1.Enabled = false;
                    imgUp1.Enabled = false;
                    imgDown1.Enabled = false;
                }
            }
        }
    }

    private void setTxtBoxTxt()
    {
    }

    #region functions created by Sampath for Report Designer

    private HtmlTable createGroupingHeader(int idx)
    {
        HtmlTable htTable = new HtmlTable();
        HtmlTableRow htRow = new HtmlTableRow();
        HtmlTableCell htCell = new HtmlTableCell();

        htTable.CellPadding = 0;
        htTable.Width = "100%";
        htTable.CellSpacing = 0;
        htTable.Border = 0;
        
        //dropdownlist

        Label lbl = new Label();
        if (idx > 1)
            lbl.Width = 530;
        else
            lbl.Width = 720;

        lbl.CssClass = "defaultFont";
        lbl.Font.Size = FontUnit.Point(9);
        lbl.Text = "&nbsp;Grouping&nbsp;" + idx.ToString() + "&nbsp;";
        lbl.Font.Bold = true;
        lbl.Height = 21;        
        lbl.Font.Italic = true;
        htCell = new HtmlTableCell();
        htCell.Controls.Add(lbl);
        htCell.Attributes.Add("class", "displaygridbottom");
        htRow.Cells.Add(htCell);

        if (idx > 1)
        {
            htCell = new HtmlTableCell();
            htCell.VAlign = "middle";
            htCell.Attributes.Add("class", "displaygridbottom");
            lbl = new Label();
            lbl.CssClass = "defaultFont";
            lbl.Font.Size = FontUnit.Point(8);
            lbl.Font.Bold = true;
            lbl.ID = "lbl_remove_" + idx.ToString();
            lbl.Text = "Remove ";
            lbl.Width = 165;            
            htCell.Align = "right";
            htCell.NoWrap = true;            
            //htCell.BgColor = "#88BAFA";
            htCell.Controls.Add(lbl);

            ImageButton iBtnRemove = new ImageButton();
            iBtnRemove.ID = "img_remove_" + idx.ToString();
            iBtnRemove.Width = 25;
            iBtnRemove.ImageUrl = "~/Images/delete.gif";
            iBtnRemove.ImageAlign = ImageAlign.AbsMiddle;
            iBtnRemove.Click += new ImageClickEventHandler(imgBut_Click);
            htCell.Controls.Add(iBtnRemove);
            htRow.Cells.Add(htCell);
        }

        htTable.Controls.Add(htRow);
        return htTable;
    }

    private HtmlTable createGroupingControls(int idx)
    { 
        HtmlTable htTable = new HtmlTable();
        HtmlTableRow htRow = new HtmlTableRow();
        HtmlTableCell htCell = new HtmlTableCell();
        LiteralControl lc = new LiteralControl();
        Label lbl = new Label();
        DropDownList ddList = new DropDownList();
        CheckBox cbField = new CheckBox();
        Button btnAdd = new Button();
        
        htTable.CellPadding = 1;
        htTable.CellSpacing = 1;
        htTable.Width = "100%";
        htTable.Border = 0;

        //dropdownlist

        htRow = new HtmlTableRow();
        createGroupCombo(ref ddList, "ddl_group_field_" + idx.ToString() , 150);
        //populateFields(lblMsgStep2.Text.Substring(lblMsgStep2.Text.IndexOf("$") + 1), ref ddList, true);
        populateFieldsFromSelectedList(ref ddList);
        htCell = new HtmlTableCell();
        htCell.Align = "Right";
        htCell.Controls.Add(ddList);
        htRow.Cells.Add(htCell);

        //label in
        lbl = new Label();
        createGroupLabel(ref lbl, "lbl_in_" + idx.ToString(), 20);
        lbl.Text = "&nbsp;In&nbsp;";
        htCell = new HtmlTableCell();
        htCell.Align = "left";
        htCell.Controls.Add(lbl);

        //ascending order
        ddList = new DropDownList();
        createGroupCombo(ref ddList, "ddl_group_order_" + idx.ToString(), 90);
        ddList.Items.Add("Ascending");
        ddList.Items.Add("Descending");
        htCell.Controls.Add(ddList);

        //order
        lbl = new Label();
        createGroupLabel(ref lbl, "lbl_order_" + idx.ToString(), 40);
        lbl.Text = "&nbsp;Order";
        htCell.Controls.Add(lbl);
        htRow.Cells.Add(htCell);
        htTable.Rows.Add(htRow);

        //CHECK BOXES - Show Subtotal, Show Header

        cbField = new CheckBox();
        createGroupCheckBox(ref cbField, "cb_showhdr_" + idx.ToString(), 190);
        cbField.Text = " Show Header ";
        cbField.AutoPostBack = true;
        cbField.CheckedChanged += new EventHandler(cbField_CheckedChanged);
        htCell = new HtmlTableCell();
        htCell.Align = "Left";
        htCell.Controls.Add(cbField);
        htCell.NoWrap = true;
        htRow.Cells.Add(htCell);

        cbField = new CheckBox();
        createGroupCheckBox(ref cbField, "cb_showsub_" + idx.ToString(), 190);
        cbField.Text = " Show Subtotal";
        cbField.AutoPostBack = true;
        cbField.CheckedChanged+=new EventHandler(cbField_CheckedChanged);
        htCell = new HtmlTableCell();
        htCell.Align = "Left";
        htCell.NoWrap = true;
        htCell.Controls.Add(cbField);
        htRow.Cells.Add(htCell);

        //Empty Rows
        htRow = new HtmlTableRow();
        htTable.Rows.Add(htRow);
        htRow = new HtmlTableRow();
        htTable.Rows.Add(htRow);

        // SHOW HEADERS ROW
        htRow = new HtmlTableRow();
        lbl = new Label();
        createGroupLabel(ref lbl, "lbl_hdr_field1_" + idx.ToString(), 150);
        lbl.Text = "Header";//    Field 1
        lbl.Font.Bold = true;
        //lbl.ForeColor = System.Drawing.Color.Blue;
        htCell = new HtmlTableCell();
        htCell.Align = "Right";
        htCell.Controls.Add(lbl);
        htRow.Cells.Add(htCell);

        ddList = new DropDownList();
        createGroupCombo(ref ddList, "ddl_hdr_field1_" + idx.ToString(), 150);
        populateFieldsFromSelectedList(ref ddList);
        //populateFields(lblMsgStep2.Text.Substring(lblMsgStep2.Text.IndexOf("$") + 1), ref ddList, true);
        htCell = new HtmlTableCell();
        htCell.Controls.Add(ddList);
        htRow.Cells.Add(htCell);

        lbl = new Label();
        createGroupLabel(ref lbl, "lbl_hdr_field2_" + idx.ToString(), 40);
        lbl.Text = "Field 2";
        htCell = new HtmlTableCell();
        htCell.Align = "right";
        htCell.Controls.Add(lbl);
        htRow.Cells.Add(htCell);

        ddList = new DropDownList();
        createGroupCombo(ref ddList, "ddl_hdr_field2_" + idx.ToString(), 150);
        //populateFields(lblMsgStep2.Text.Substring(lblMsgStep2.Text.IndexOf("$") + 1), ref ddList, true);
        populateFieldsFromSelectedList(ref ddList);
        htCell.NoWrap = true;
        htCell.Controls.Add(ddList);
        htRow.Cells.Add(htCell);

        lbl = new Label();
        createGroupLabel(ref lbl, "lbl_hdr_field3_" + idx.ToString(), 40);
        lbl.Text = "Field 3";
        htCell = new HtmlTableCell();
        htCell.Align = "right";
        htCell.Controls.Add(lbl);

        ddList = new DropDownList();
        createGroupCombo(ref ddList, "ddl_hdr_field3_" + idx.ToString(), 150);
        //populateFields(lblMsgStep2.Text.Substring(lblMsgStep2.Text.IndexOf("$") + 1), ref ddList, true);
        populateFieldsFromSelectedList(ref ddList);
        htCell.Controls.Add(ddList);
        htCell.NoWrap = true;
        htRow.Cells.Add(htCell);
        htTable.Rows.Add(htRow);

        //SUBTOTAL ROW
        htRow = new HtmlTableRow();
        lbl = new Label();
        createGroupLabel(ref lbl, "lbl_tot_field1_" + idx.ToString(), 150);
        lbl.Text = "Subtotal";//      Field 1
        lbl.Font.Bold = true;
        //lbl.ForeColor = System.Drawing.Color.Blue;
        htCell = new HtmlTableCell();
        htCell.Align = "Right";
        htCell.Controls.Add(lbl);
        htRow.Cells.Add(htCell);

        ddList = new DropDownList();
        createGroupCombo(ref ddList, "ddl_tot_field1_" + idx.ToString(), 150);
        //populateFields(lblMsgStep2.Text.Substring(lblMsgStep2.Text.IndexOf("$") + 1), ref ddList, true);
        //populateFieldsFromSelectedList(ref ddList);
        if (lblMsgStep2.Text.Trim() != "" && lblMsgStep2.Text.Contains("$"))
            populateNumericFields(ref ddList, lblMsgStep2.Text.Substring(lblMsgStep2.Text.IndexOf("$") + 1));
        htCell = new HtmlTableCell();
        htCell.Controls.Add(ddList);
        htRow.Cells.Add(htCell);

        lbl = new Label();
        createGroupLabel(ref lbl, "lbl_tot_field2_" + idx.ToString(), 40);
        lbl.Text = "Field 2";
        htCell = new HtmlTableCell();
        htCell.Align = "right";
        htCell.Controls.Add(lbl);
        htRow.Cells.Add(htCell);

        ddList = new DropDownList();
        createGroupCombo(ref ddList, "ddl_tot_field2_" + idx.ToString(), 150);
        //populateFields(lblMsgStep2.Text.Substring(lblMsgStep2.Text.IndexOf("$") + 1), ref ddList, true);
        if (lblMsgStep2.Text.Trim() != "" && lblMsgStep2.Text.Contains("$"))
            populateNumericFields(ref ddList, lblMsgStep2.Text.Substring(lblMsgStep2.Text.IndexOf("$") + 1));
        //populateFieldsFromSelectedList(ref ddList);
        htCell.Controls.Add(ddList);
        htCell.NoWrap = true;
        htRow.Cells.Add(htCell);

        lbl = new Label();
        createGroupLabel(ref lbl, "lbl_tot_field3_" + idx.ToString(), 40);
        lbl.Text = "Field 3";
        htCell = new HtmlTableCell();
        htCell.Align = "right";
        htCell.Controls.Add(lbl);

        ddList = new DropDownList();
        createGroupCombo(ref ddList, "ddl_tot_field3_" + idx.ToString(), 150);
        //populateFields(lblMsgStep2.Text.Substring(lblMsgStep2.Text.IndexOf("$") + 1), ref ddList, true);
        //populateFieldsFromSelectedList(ref ddList);
        if (lblMsgStep2.Text.Trim() != "" && lblMsgStep2.Text.Contains("$"))
            populateNumericFields(ref ddList, lblMsgStep2.Text.Substring(lblMsgStep2.Text.IndexOf("$") + 1));
        htCell.NoWrap = true;
        htCell.Controls.Add(ddList);
        htRow.Cells.Add(htCell);
        htTable.Rows.Add(htRow);

        lc.Text = " ";
        htCell = new HtmlTableCell();
        htCell.Width = "150";
        htCell.Controls.Add(lc);
        htRow.Cells.Add(htCell);

        lc = new LiteralControl();
        lc.Text = " ";
        htCell = new HtmlTableCell();
        htCell.Width = "150";
        htCell.Controls.Add(lc);
        htRow.Cells.Add(htCell);

        lc = new LiteralControl();
        lc.Text = " ";
        htCell = new HtmlTableCell();
        htCell.Width = "190";
        htCell.Controls.Add(lc);
        htRow.Cells.Add(htCell);
        htTable.Rows.Add(htRow);
        return htTable;
    }

    private void removeRows(DataTable dtToRemove, DataRow[] drToRemove)
    {
        //sanal
        try
        {
            DataTable dtt = dtToRemove.Clone(); //creates a cloned datatable with the same structure

            for (int i = 0; i < drToRemove.Length; i++) //imports all the filtered data to the new table
                dtt.ImportRow(drToRemove[i]);

            dtToRemove.Rows.Clear();	//removes all the rows from original table
            //dtToRemove.AcceptChanges();

            foreach (DataRow drr in dtt.Rows) //adds the rows from temp dtt table to the original table
                dtToRemove.ImportRow(drr);
            dtt = null;

        }
        catch (Exception ee)
        {
            
        }
        //sanal
    }

    void imgBut_Click(object sender, ImageClickEventArgs e)
    {
        try
        {
            string btnID = ((ImageButton)(sender)).ID;
            int idx = Convert.ToInt32(btnID.Substring(btnID.LastIndexOf("_") + 1));
            DataSet tmpDS = (DataSet) Session["report_ds"];
            if (tmpDS != null)
            {
                DataTable dt = tmpDS.Tables["p_report_grouping"];
                if (dt != null)
                {
                    DataRow[] drF = dt.Select("attribute_sequence<>" + idx.ToString());
                    removeRows(dt, drF);
                }

                dt = null;
                dt = tmpDS.Tables["p_report_grouping_header"];
                if (dt != null)
                {
                    DataRow[] drF = dt.Select("group_sequence<>" + idx.ToString());
                    removeRows(dt, drF);
                }

                dt = null;
                dt = tmpDS.Tables["p_report_grouping_subtotal"];
                if (dt != null)
                {
                    DataRow[] drF = dt.Select("group_sequence<>" + idx.ToString());
                    removeRows(dt, drF);
                }
                dt = null;

                idx = Convert.ToInt32(hiddenGroupCnt.Value);

                HtmlTable tblToRemove = (HtmlTable)this.Master.FindControl("ContentPlaceHolder3").FindControl("wz_report").FindControl("placeholder_group").FindControl("httable_hdr_" + idx.ToString());
                this.Master.FindControl("ContentPlaceHolder3").FindControl("wz_report").FindControl("placeholder_group").Controls.Remove(tblToRemove);

                tblToRemove = (HtmlTable)this.Master.FindControl("ContentPlaceHolder3").FindControl("wz_report").FindControl("placeholder_group").FindControl("httable_det_" + idx.ToString());
                this.Master.FindControl("ContentPlaceHolder3").FindControl("wz_report").FindControl("placeholder_group").Controls.Remove(tblToRemove);

                hiddenGroupCnt.Value = (Convert.ToInt32(hiddenGroupCnt.Value) - 1).ToString();
                
                //createGroupingForm(Convert.ToInt32(hiddenGroupCnt.Value));
                //substitute_step_values(2);
                //Session["groupCount"] = hiddenGroupCnt.Value;
                btnAddGrouping.ForeColor = System.Drawing.Color.Black;
                lblAddGrouping.ForeColor = System.Drawing.Color.Black;

                collect_step_values(2);                
            }
            
        }
        catch (Exception ex)
        { 

        }
    }

    private void createGroupingForm(int idx)
    {
        if (idx > 3)
        {
            btnAddGrouping.Enabled = false;
            return;
        }
        else
            btnAddGrouping.Enabled = true;

        if (lblMsgStep2.Text.Trim() == "") return;

        HtmlForm frmObj = (HtmlForm)this.Master.FindControl("Form1");
        PlaceHolder cph = (PlaceHolder) wz_Report.FindControl("PlaceHolder_group");
        HtmlTable htTable = null;
        if (cph != null)
        {
            htTable = createGroupingHeader(idx);
            htTable.ID = "httable_hdr_" + idx.ToString();
            cph.Controls.Add(htTable);

            htTable = createGroupingControls(idx);
            htTable.ID = "httable_det_" + idx.ToString();
            cph.Controls.Add(htTable);

            //hiddenGroupCnt.Value = idx.ToString();
            //Session["groupCount"] = idx;
        }
    }

    private void createGroupCheckBox(ref CheckBox cbField, string ID, int width)
    {
        cbField = new CheckBox();
        cbField.ID = ID;
        cbField.Checked = true;      
        cbField.Width = width;
        cbField.CssClass = "defaultFont";
        cbField.Font.Size = FontUnit.Point(8);
    }

    void cbField_CheckedChanged(object sender, EventArgs e)
    {
        try
        {
            CheckBox cb = ((CheckBox)(sender));
            string chboxID = ((CheckBox)(sender)).ID;
            int idx = Convert.ToInt32(chboxID.Substring(chboxID.LastIndexOf("_") + 1));
            if (cb.ID.ToLower().StartsWith("cb_showhdr_"))
            {
                Label lbl = null;
                DropDownList ddList = null;
                if (cb.Checked)
                {
                    lbl = (Label)this.Master.FindControl("ContentPlaceHolder3").FindControl("wz_report").FindControl("lbl_hdr_field1_" + idx.ToString());
                    lbl.Enabled = true;

                    ddList = (DropDownList)this.Master.FindControl("ContentPlaceHolder3").FindControl("wz_report").FindControl("ddl_hdr_field1_" + idx.ToString());
                    ddList.Enabled = true;

                    lbl = (Label)this.Master.FindControl("ContentPlaceHolder3").FindControl("wz_report").FindControl("lbl_hdr_field2_" + idx.ToString());
                    lbl.Enabled = true;

                    ddList = (DropDownList)this.Master.FindControl("ContentPlaceHolder3").FindControl("wz_report").FindControl("ddl_hdr_field2_" + idx.ToString());
                    ddList.Enabled = true;

                    lbl = (Label)this.Master.FindControl("ContentPlaceHolder3").FindControl("wz_report").FindControl("lbl_hdr_field3_" + idx.ToString());
                    lbl.Enabled = true;

                    ddList = (DropDownList)this.Master.FindControl("ContentPlaceHolder3").FindControl("wz_report").FindControl("ddl_hdr_field3_" + idx.ToString());
                    ddList.Enabled = true;
                }
                else
                {
                    lbl = (Label)this.Master.FindControl("ContentPlaceHolder3").FindControl("wz_report").FindControl("lbl_hdr_field1_" + idx.ToString());
                    lbl.Enabled = false;

                    ddList = (DropDownList)this.Master.FindControl("ContentPlaceHolder3").FindControl("wz_report").FindControl("ddl_hdr_field1_" + idx.ToString());
                    ddList.SelectedIndex = -1;
                    ddList.Enabled = false;

                    lbl = (Label)this.Master.FindControl("ContentPlaceHolder3").FindControl("wz_report").FindControl("lbl_hdr_field2_" + idx.ToString());
                    lbl.Enabled = true;

                    ddList = (DropDownList)this.Master.FindControl("ContentPlaceHolder3").FindControl("wz_report").FindControl("ddl_hdr_field2_" + idx.ToString());
                    ddList.SelectedIndex = -1;
                    ddList.Enabled = false;

                    lbl = (Label)this.Master.FindControl("ContentPlaceHolder3").FindControl("wz_report").FindControl("lbl_hdr_field3_" + idx.ToString());
                    lbl.Enabled = true;

                    ddList = (DropDownList)this.Master.FindControl("ContentPlaceHolder3").FindControl("wz_report").FindControl("ddl_hdr_field3_" + idx.ToString());
                    ddList.SelectedIndex = -1;
                    ddList.Enabled = false;
                }
            }
            else if (cb.ID.ToLower().StartsWith("cb_showsub_"))
            {
                Label lbl = null;
                DropDownList ddList = null;
                if (cb.Checked)
                {
                    lbl = (Label)this.Master.FindControl("ContentPlaceHolder3").FindControl("wz_report").FindControl("lbl_tot_field1_" + idx.ToString());
                    lbl.Enabled = true;

                    ddList = (DropDownList)this.Master.FindControl("ContentPlaceHolder3").FindControl("wz_report").FindControl("ddl_tot_field1_" + idx.ToString());
                    ddList.Enabled = true;

                    lbl = (Label)this.Master.FindControl("ContentPlaceHolder3").FindControl("wz_report").FindControl("lbl_tot_field2_" + idx.ToString());
                    lbl.Enabled = true;

                    ddList = (DropDownList)this.Master.FindControl("ContentPlaceHolder3").FindControl("wz_report").FindControl("ddl_tot_field2_" + idx.ToString());
                    ddList.Enabled = true;

                    lbl = (Label)this.Master.FindControl("ContentPlaceHolder3").FindControl("wz_report").FindControl("lbl_tot_field3_" + idx.ToString());
                    lbl.Enabled = true;

                    ddList = (DropDownList)this.Master.FindControl("ContentPlaceHolder3").FindControl("wz_report").FindControl("ddl_tot_field3_" + idx.ToString());
                    ddList.Enabled = true;
                }
                else
                {
                    lbl = (Label)this.Master.FindControl("ContentPlaceHolder3").FindControl("wz_report").FindControl("lbl_tot_field1_" + idx.ToString());
                    lbl.Enabled = false;

                    ddList = (DropDownList)this.Master.FindControl("ContentPlaceHolder3").FindControl("wz_report").FindControl("ddl_tot_field1_" + idx.ToString());
                    ddList.SelectedIndex = -1;
                    ddList.Enabled = false;

                    lbl = (Label)this.Master.FindControl("ContentPlaceHolder3").FindControl("wz_report").FindControl("lbl_tot_field2_" + idx.ToString());
                    lbl.Enabled = true;

                    ddList = (DropDownList)this.Master.FindControl("ContentPlaceHolder3").FindControl("wz_report").FindControl("ddl_tot_field2_" + idx.ToString());
                    ddList.SelectedIndex = -1;
                    ddList.Enabled = false;

                    lbl = (Label)this.Master.FindControl("ContentPlaceHolder3").FindControl("wz_report").FindControl("lbl_tot_field3_" + idx.ToString());
                    lbl.Enabled = true;

                    ddList = (DropDownList)this.Master.FindControl("ContentPlaceHolder3").FindControl("wz_report").FindControl("ddl_tot_field3_" + idx.ToString());
                    ddList.SelectedIndex = -1;
                    ddList.Enabled = false;
                }
            }
            collect_step_values(2);
            //substitute_step_values(2);
            if (Convert.ToInt32(hiddenGroupCnt.Value) == 3)
            {
                lblAddGrouping.ForeColor = System.Drawing.Color.LightGray;
                btnAddGrouping.Enabled = false;
            }
        }
        catch (Exception ex)
        { 
        }
    }

    private void createGroupCombo(ref DropDownList ddLst, string ID, int width)
    {
        ddLst = new DropDownList();
        ddLst.ID = ID;
        ddLst.Width = width;
        ddLst.CssClass = "defaultFont";
        ddLst.Font.Size = FontUnit.Point(8);
    }

    private void createGroupLabel(ref Label lbl, string ID, int width)
    {
        lbl = new Label();
        lbl.ID = ID;
        lbl.Width = width;
        //lbl.BorderStyle = BorderStyle.None;
        lbl.CssClass = "defaultFont";
        lbl.Font.Size = FontUnit.Point(8);
    }
    
    #endregion

    private void populateFields(string ObjectId, ref DropDownList ddList, bool addNone)
    {
        string sSql = "Select * from sy_obj";
        dtObj = hdd.GetDataTable(sSql);
        DataRow[] drr = dtObj.Select("object_id='" + ObjectId + "'");
        if (drr.Length > 0)
        {
            //lblDesc1.Text = drr[0]["object_description"].ToString();
            ddList.Items.Clear();
            if (addNone)
                ddList.Items.Add(new ListItem("---None---", ""));

            sSql = "Select * from sy_obj_mas_detail where object_id = '" + drr[0]["af_row_id"].ToString() + "'";

            DataTable dtFields = hdd.GetDataTable(sSql);

            foreach (DataRow dr in dtFields.Select())
            {
                string sAttrib_Name = dr["attrib_id"].ToString();

                if (dr["attrib_id"].ToString() != "af_row_id")
                {
                    ListItem liObject = new ListItem(sAttrib_Name, "[" + dr["master_obj"].ToString() + "].[" + sAttrib_Name + "]");
                    ddList.Items.Add(liObject);
                }
            }

            sSql = "Select * from sy_obj_att where object_id = '" + drr[0]["af_row_id"].ToString() + "'";

            dtFields = hdd.GetDataTable(sSql);

            foreach (DataRow dr in dtFields.Select())
            {
                string sAttrib_Name = "";
                if (dr["attrib_name"].ToString() == "")
                    sAttrib_Name = dr["attrib_id"].ToString();
                else
                    sAttrib_Name = dr["attrib_name"].ToString();
                if (dr["attrib_id"].ToString() != "af_row_id")
                {
                    ListItem liObject = new ListItem(sAttrib_Name, "[" + ObjectId + "].[" + dr["attrib_id"].ToString() + "]");
                    ddList.Items.Add(liObject);
                }
            }
            dtFields.Dispose();
            dtFields = null;
        }
        else
        { 
            DataRow dr = hdd.GetTableRow("select * from sy_report_sql where report_base_id='" + ObjectId + "'");
            if (dr != null)
            {
                ddList.Items.Clear();
                if (addNone)
                    ddList.Items.Add(new ListItem("---None---", ""));

                DataTable dtQuery = null;
                sSql = dr["report_base_sql"].ToString();
                if (sSql.Contains("$") || sSql.Contains("#"))
                {
                    dr = null;
                    return;
                }

                if (sSql != "")
                {
                    dtQuery = hdd.GetDataTable(sSql);
                    if (dtQuery != null)
                    {
                        foreach (DataColumn dc in dtQuery.Columns)
                        {
                            ListItem li = new ListItem("[" + dr["report_base_name"].ToString() + "].[" + dc.ColumnName + "]", "[" + ObjectId + "].[" + dc.ColumnName + "]");
                            ddList.Items.Add(li);
                        }
                    }
                }
                dtQuery = null;
            }
            dr = null;
        }
    }

    private void createYesNoCombo(ref DropDownList yesNo, string ID, int width)
    {
        yesNo = new DropDownList();
        yesNo.Items.Add("No");
        yesNo.Items.Add("Yes");

        yesNo.ID = ID;
        yesNo.Width = width;
        //yesNo.BorderStyle = BorderStyle.None;
        yesNo.CssClass = "defaultFont";
        yesNo.Font.Size = FontUnit.Point(8);
    }

    private void showFieldProperties()
    {
        HtmlForm frmObj = (HtmlForm)this.Master.FindControl("Form1");
        htProperties = (HtmlTable)frmObj.FindControl("ContentPlaceHolder3").FindControl("wz_report").FindControl("tblproperties");
        HtmlTableRow htr = new HtmlTableRow();
        HtmlTableCell htc = new HtmlTableCell();
        Label lbl = new Label();

        if (htProperties != null)
        {            
            htProperties.CellSpacing = 0;
            htProperties.CellPadding = 0;
            htProperties.Border = 0;
            for (int iCount = 0; iCount < lstSelectedFields1.Items.Count; iCount++)
            {
                ListItem li = lstSelectedFields1.Items[iCount];
                htr = new HtmlTableRow();

                lbl = new Label();
                lbl.ID = "lbl_caption_" + li.Value;
                lbl.Text = li.Text;
                lbl.CssClass = "defaultFont";
                lbl.Font.Size = FontUnit.Point(8);
                htc = new HtmlTableCell();
                htc.Controls.Add(lbl);
                htr.Cells.Add(htc);

                string sAttributeName = "";
                if (IsEdit) sAttributeName = getFieldCaption(li.Value);
                if (sAttributeName == "")
                    sAttributeName = li.Text.Substring(li.Text.IndexOf("].[") + 3, li.Text.Length - 1 - (li.Text.IndexOf("].[") + 3));

                TextBox txtBox = new TextBox();
                txtBox.Text = sAttributeName;
                txtBox.ID = "txt_" + li.Value;
                txtBox.Width = 250;
                //txtBox.BorderStyle = BorderStyle.None;
                //txtBox.BorderColor = System.Drawing.Color.Gainsboro;
                txtBox.CssClass = "defaultFont";
                txtBox.Font.Size = FontUnit.Point(8);
                htc = new HtmlTableCell();
                htc.Controls.Add(txtBox);
                htr.Cells.Add(htc);

                DropDownList yesNo = new DropDownList();
                createYesNoCombo(ref yesNo, "dd_" + li.Value + "_bold", 50);
                htc = new HtmlTableCell();
                htc.Controls.Add(yesNo);
                htr.Cells.Add(htc);

                createYesNoCombo(ref yesNo, "dd_" + li.Value + "_wwrap", 70);
                yesNo.SelectedIndex = 0;
                htc = new HtmlTableCell();
                htc.Controls.Add(yesNo);
                htr.Cells.Add(htc);
                
                htr.Height = "25px";
                int iRow = (iCount + 1) % 2;
                htr.Attributes.Add("Class", "Grid_Row" + iRow.ToString());
                htProperties.Rows.Add(htr);
            }
            //htcField.Controls.Add(ht);
        }
    }

    protected void btnSave_Click(object sender, EventArgs e)
    {
        collect_step_values(wz_Report.ActiveStepIndex);
        if (SaveData())
            lblMessage.Text = "Data inserted successfully";
    }

    private void fillDefaultColumns(ref DataRow dr, string sCurrentDate)
    {
        string ownerafrowid = getUseraf_row_idfromUser(txt_owner_id.Text);
        if (dr["created_by"] == DBNull.Value)
        {
            dr["created_by"] = Session["user_afrowid"].ToString();
            //dr["owner_id"] = Session["user_afrowid"].ToString(); // Added by srivatsan on June 15 2009 for owner id field
            //dr["owner_id"] = ddownerid.SelectedValue;


            if (ownerafrowid != "")
            {
                owner_id.Value = ownerafrowid;
                dr["owner_id"] = owner_id.Value;
            }
            else
            {
                lblMessage.Text = "&nbsp;<img src='Images/Error.gif' border='0'>&nbsp;Invalid data for Owner :" + txt_owner_id.Text;
                return;
            }


            

            dr["created_at"] = sCurrentDate;
        }
        //if (IsEdit)
        //{
        //    dr["created_by"] = GlobalValues.dsAudit.Tables[0].Rows[0]["created_by"];
        //    //dr["owner_id"] = GlobalValues.dsAudit.Tables[0].Rows[0]["owner_id"];// Added by srivatsan on June 15 2009 for owner id field
        //    //dr["owner_id"] = ddownerid.SelectedValue;
        //    if (ownerafrowid != "")
        //    {
        //        owner_id.Value = ownerafrowid;
        //        dr["owner_id"] = owner_id.Value;
        //    }
        //    else
        //    {
        //        lblMessage.Text = "&nbsp;<img src='Images/Error.gif' border='0'>&nbsp;Invalid data for Owner :" + txt_owner_id.Text;
        //        return;
        //    }
        //    dr["created_at"] = GlobalValues.dsAudit.Tables[0].Rows[0]["created_at"];
        //}
        dr["modified_by"] = Session["user_afrowid"].ToString();
        dr["modified_at"] = sCurrentDate;
    }

    private string getCurrency(string user_afrowid)
    {
        string retCurr = "USD";
        
        try
        {
            DataTable dt = new DataTable();
            dt = hdd.GetDataTable("select currency_id from sy_usr where af_row_id='" + user_afrowid + "'");
            if (dt.Rows.Count > 0)
                retCurr = dt.Rows[0]["currency_id"].ToString();
            dt = null;
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("getCurrency: Error: " + ex.Message);
        }
        return retCurr;
    }

    private string getCaption(string rptSrc, string attrib_id, string caption)
    {
        string retCaption = "";
        try
        {
            if (caption != "") return caption; // Added by 'Imran Gani' on 06-Mar-2014, for Report Caption
            if (rptSrc.ToLower() == "object")
            {
                string tmpSQL = "";
                if (attrib_id.IndexOf("].[") == -1)
                    tmpSQL = "select attrib_name from sy_obj_att where af_row_id='" + attrib_id + "'";
                else
                    tmpSQL = "select attrib_name from sy_obj_att where af_row_id='" + attrib_id.Substring(attrib_id.IndexOf("].[") + 3).TrimEnd(']') + "'";

                DataTable dtt = hdd.GetDataTable(tmpSQL);
                #region Old code commented by 'Imran Gani' on 06-Mar-2014, for Report Caption
                //if (dtt == null)
                //    retCaption = caption;
                //else
                //{
                //    if (dtt.Rows.Count == 0)
                //        retCaption = caption;
                //    else
                //    {
                //        if (dtt.Rows[0]["attrib_name"].ToString().ToLower() == caption.ToLower())
                //            retCaption = "";
                //        else
                //            retCaption = caption;
                //    }
                //}
                #endregion
                if (dtt == null || dtt.Rows.Count == 0) // Added by 'Imran Gani' on 06-Mar-2014, for Report Caption
                    retCaption = caption;
                else
                    retCaption = dtt.Rows[0]["attrib_name"].ToString();
                dtt = null;
            }
            else if (lblReportSrc.Text.ToLower() == "sql")
                retCaption = caption;
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("getCaption : Error : " + ex.Message);
        }
        return retCaption;
    }

    private string setCaption(string rptSrc, string attrib_id, string caption)
    {
        string retCaption = "";
        try
        {
            if (rptSrc.ToLower() == "object")
            {
                string tmpSQL = ""; 
                if (attrib_id.IndexOf("].[")==-1)
                    tmpSQL = "select attrib_name from sy_obj_att where af_row_id='" + attrib_id + "'";
                else
                    tmpSQL = "select attrib_name from sy_obj_att where af_row_id='" + attrib_id.Substring(attrib_id.IndexOf("].[") + 3).TrimEnd(']') + "'";

                DataTable dtt = hdd.GetDataTable(tmpSQL);
                if (dtt == null)
                    retCaption = caption;
                else
                {
                    if (dtt.Rows.Count == 0)
                        retCaption = caption;
                    else
                    {
                        if (caption.Trim() == "")
                            retCaption = dtt.Rows[0]["attrib_name"].ToString();
                        else
                            retCaption = caption;
                    }
                }
                dtt = null;
            }
            else if (lblReportSrc.Text.ToLower() == "sql")
                retCaption = caption;
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("setCaption : Error : " + ex.Message);
        }
        return retCaption;
    }

    private string getDataType(string af_row_id)
    {
        string retDataType = "TX";
        try
        {
            string tmpSQL = "";
            if (af_row_id.IndexOf("].[") == -1)
                tmpSQL = "select attrib_data_type from sy_obj_att where af_row_id='" + af_row_id + "'";
            else
                tmpSQL = "select attrib_data_type from sy_obj_att where af_row_id='" + af_row_id.Substring(af_row_id.IndexOf("].[") + 3).TrimEnd(']') + "'";

            DataTable dtt = new DataTable();
            dtt = hdd.GetDataTable(tmpSQL);
            if (dtt.Rows.Count > 0)
                retDataType = dtt.Rows[0]["attrib_data_type"].ToString().ToUpper();
            dtt = null;
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("checkCurrency: Error: " + ex.Message);
        }
        return retDataType;
    }

    private string getAttribAlignment(string rptSrc, string af_row_id)
    {
        string retAlign = "6"; //6=middleleft, 8=middleright
        try
        {
            string retDataType = "";
            if (rptSrc.ToLower() == "object")
            {
                string tmpSQL = "";
                if (af_row_id.IndexOf("].[") == -1)
                    tmpSQL = "select attrib_data_type from sy_obj_att where af_row_id='" + af_row_id + "'";
                else
                    tmpSQL = "select attrib_data_type from sy_obj_att where af_row_id='" + af_row_id.Substring(af_row_id.IndexOf("].[") + 3).TrimEnd(']') + "'";

                DataTable dtt = hdd.GetDataTable(tmpSQL);
                if (dtt == null)
                    retDataType = "TX";
                else
                {
                    if (dtt.Rows.Count == 0)
                        retDataType = "TX";
                    else
                        retDataType = dtt.Rows[0]["attrib_data_type"].ToString();
                }
                if (retDataType.ToUpper() == "BO" || retDataType.ToUpper() == "DT" || retDataType.ToUpper() == "DA")
                    retDataType = "TX";
                dtt = null;
            }
            else if (lblReportSrc.Text.ToLower() == "sql")
                retDataType = "TX";

            if (retDataType == "TX")
                retAlign = "6";
            else //CU, NU, DC
                retAlign = "8";
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("getAttribAlignment : Error : " + ex.Message);
        }
        return retAlign;
    }

    private string getAttribId(string rptSrc, string af_row_id)
    {
        string retAttribId = "";
        try
        {
            if (rptSrc.ToLower() == "object")
            {
                string tmpSQL = "";
                if (af_row_id.IndexOf("].[")==-1)
                    tmpSQL = "select attrib_id from sy_obj_att where af_row_id='" + af_row_id + "'";
                else
                    tmpSQL = "select attrib_id from sy_obj_att where af_row_id='" + af_row_id.Substring(af_row_id.IndexOf("].[") + 3).TrimEnd(']') + "'";

                DataTable dtt = hdd.GetDataTable(tmpSQL);
                if (dtt == null)
                    retAttribId = af_row_id;
                else
                {
                    if (dtt.Rows.Count == 0)
                        retAttribId = af_row_id;
                    else
                        retAttribId = dtt.Rows[0]["attrib_id"].ToString();
                }
                dtt = null;
            }
            else if (lblReportSrc.Text.ToLower() == "sql")
                retAttribId = af_row_id;
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("getAttribId : Error : " + ex.Message);
        }
        return retAttribId;
    }

    private void addColumns(ref DataSet dsReport, DataTable dtaPage, DataTable dtaPageCtrl)
    {
        try
        {
            DataRow droPage;
            DataRow[] droPageCtrl;
            DataColumn dtcObj;            
            for (int i = 0; i < dtaPage.Rows.Count; i++)
            {
                droPage = dtaPage.Rows[i];
                DataTable dtaObj = dsReport.Tables[droPage["page_id"].ToString()];
                if (dtaObj == null)
                    dtaObj = new DataTable(droPage["page_id"].ToString());
                droPageCtrl = dtaPageCtrl.Select("page_id='" + droPage["af_row_id"].ToString() + "'");
                for (int j = 0; j < droPageCtrl.Length; j++)
                {
                    if (dtaObj.Columns.Contains(droPageCtrl[j]["control_attrib_id"].ToString()))
                        continue;
                    dtcObj = new DataColumn();
                    dtcObj.ColumnName = droPageCtrl[j]["control_attrib_id"].ToString();
                    dtaObj.Columns.Add(dtcObj);
                }
                if (!dsReport.Tables.Contains(dtaObj.TableName))
                    dsReport.Tables.Add(dtaObj);
                dtaObj = null;
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("addColumns : Error : " + ex.Message);
        }
    }

    private string getReportName(string af_row_id)
    {
        string retVal = "";
        try
        {
            DataTable dt = new DataTable();
            dt = hdd.GetDataTable("select isnull(rpt_name,'')[rpt_name] from sy_report where af_row_id='" + af_row_id + "'");
            if (dt.Rows.Count > 0)
                retVal = dt.Rows[0]["rpt_name"].ToString();
            dt = null;
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("getReportName : Error : " + ex.Message);
        }
        return retVal;
    }
    #region commented for Asp.net report viewr control implementation
    private bool fillInputData(ref DataSet dsReport)
    {
        bool bReturn = true;
        string group_af_row_id = "";
        string rpt_name = "";
        try
        {
            if (dsReport == null)
            {
                cancelClick();
                return false;
            }
            rpt_name = getReportName(hf_af_row_id1.Value);
            if (hiddenTmp.Value == "SaveAs")
            {
                hiddenTmp.Value = "SaveAsNew";
                if (rpt_name.Trim() != string.Empty)
                {
                    wz_Report.ActiveStepIndex = 5;
                    txtRepName.Focus();
                    DynamicDisplayI ddI = new DynamicDisplayI();
                    Menu mnu = (Menu)ddI.FindControl(Master.FindControl("ContentPlaceHolder3").FindControl("wz_report").Controls, "mnu_options_step2");
                    if (mnu != null)
                        mnu.Items.Remove(mnu.Items[1]);
                    ddI = null;
                    return false;
                }
            }

            if (txtRepName.Text.Trim() == string.Empty)
            {
                wz_Report.ActiveStepIndex = 5;
                txtRepName.Focus();
                return false;
            }
            HtmlForm frmObj = (HtmlForm)this.Master.FindControl("Form1");
            HtmlTable htProperties = (HtmlTable)frmObj.FindControl("ContentPlaceHolder3").FindControl("wz_report").FindControl("tblproperties");
            ScreenReader SR = new ScreenReader();
            string sCurrentDate = DateTime.Now.ToString();

            if (htProperties != null)
            {
                string sPageSetId = m_PageSetId;
                string sReportId = "";
                ScreenReader objSR = new ScreenReader();

                if (hiddenTmp.Value == "SaveAsNew")
                {
                    //check for report name                    
                    if (txtRepName.Text.ToLower().Trim() != rpt_name.ToLower() && rpt_name.Trim() != string.Empty)
                    {
                        IsEdit = false;
                        hf_af_row_id1.Value = SR.getHashKey();
                    }
                }

                bool is_Copy = checkIsCopy(ref dsReport);

                if (!IsEdit)
                    addColumns(ref dsReport, dsPageInfo.Tables["Page"], dsPageInfo.Tables["PageCtrl"]);
                //objSR.CreatePageDataTable(dsReport, dsPageInfo.Tables["Page"], dsPageInfo.Tables["PageCtrl"]);

                sReportId = hdd.GetColumnValue("Select count(rpt_id) from sy_report");
                if (!IsEdit)
                {
                    if (hiddenTmp.Value == "SaveAsNew")
                    {
                        IsEdit = false;
                        if (sReportId == "")
                            sReportId = "1";
                        else
                            sReportId = Convert.ToString(Convert.ToInt16(sReportId) + 1);
                    }
                    else if (lblReportId.Text.Trim() != "" && !is_Copy) //
                    {
                        sReportId = dsReport.Tables["p_sy_report"].Rows[0]["rpt_id"].ToString();
                        IsEdit = true;
                        //GlobalValues.dsAudit = dsReport; //Commanded by 'Imran Gani' on 24/02/2012, to avoid GlobalValues.dsAufit.
                    }
                    else
                    {
                        if (sReportId == "")
                            sReportId = "1";
                        else
                            sReportId = Convert.ToString(Convert.ToInt16(sReportId) + 1);
                    }
                }
                else
                    sReportId = m_Report_id;

                if (dsReport.Tables["p_sy_report"] != null)
                {
                    if (IsEdit)
                    {
                        DataTable dt = dsReport.Tables["p_sy_report"];
                        dt.Rows[0]["rpt_id"] = sReportId;
                        dt.Rows[0]["rpt_name"] = txtRepName.Text.Trim();
                        dt.Rows[0]["rpt_desc"] = txtReportDesc.Text.Trim();
                        dt.Rows[0]["rpt_base_object"] = lblReportSrc.Text;
                        dt.Rows[0]["report_category"] = txtReportCategory.Text; // Added by 'Imran Gani' on 28-May-2012, for report category.
                        DataRow dr = dt.Rows[0];
                        fillDefaultColumns(ref dr, sCurrentDate);
                        dr = null;
                    }
                    else
                    {
                        DataRow dr = dsReport.Tables["p_sy_report"].Rows[0];
                        dsReport.Tables["p_sy_report"].Rows[0]["af_row_id"] = hf_af_row_id1.Value;
                        dsReport.Tables["p_sy_report"].Rows[0]["rpt_base_object"] = lblReportSrc.Text;
                        dsReport.Tables["p_sy_report"].Rows[0]["rpt_name"] = txtRepName.Text.Trim();
                        dsReport.Tables["p_sy_report"].Rows[0]["rpt_base_object"] = lblReportSrc.Text;
                        //dsReport.Tables["p_sy_report"].Rows[0]["rpt_id"] = sReportId;
                        dsReport.Tables["p_sy_report"].Rows[0]["rpt_id"] = sReportId;
                        dsReport.Tables["p_sy_report"].Rows[0]["report_category"] = txtReportCategory.Text; // Added by 'Imran Gani' on 28-May-2012, for report category.
                        fillDefaultColumns(ref dr, sCurrentDate);
                        dr = null;
                    }
                    //else
                    //{
                    //    DataRow drReport = dsReport.Tables["p_sy_report"].NewRow();
                    //    if (drReport != null)
                    //    {
                    //        drReport["af_row_id"] = hf_af_row_id1.Value;
                    //        drReport["rpt_id"] = sReportId;
                    //        drReport["rpt_name"] = txtRepName.Text.Trim();
                    //        drReport["rpt_desc"] = txtReportDesc.Text.Trim();
                    //        drReport["rpt_base_object"] = lblReportSrc.Text;
                    //        fillDefaultColumns(ref drReport, sCurrentDate);
                    //    }
                    //    dsReport.Tables["p_sy_report"].Rows.Add(drReport);
                    //}
                }

                if (dsReport.Tables["p_sy_report_obj"] != null)
                {
                    if (dsReport.Tables["p_sy_report_obj"].Rows.Count == 0)
                    {
                        DataRow drReport = dsReport.Tables["p_sy_report_obj"].NewRow();
                        drReport["af_row_id"] = SR.getHashKey();
                        drReport["rpt_id"] = hf_af_row_id1.Value;
                        drReport["object_id"] = cmbObjects.SelectedValue.Substring(cmbObjects.SelectedValue.IndexOf("@") + 1);
                        fillDefaultColumns(ref drReport, sCurrentDate);
                        dsReport.Tables["p_sy_report_obj"].Rows.Add(drReport);
                    }
                    else
                    {
                        DataRow dr = dsReport.Tables["p_sy_report_obj"].Rows[0];
                        string sTemp = dr["af_row_id"].ToString();
                        if (sTemp == "" || IsEdit == false) sTemp = SR.getHashKey();
                        dr["af_row_id"] = sTemp;
                        dr["rpt_id"] = hf_af_row_id1.Value;
                        dr["object_id"] = cmbObjects.SelectedValue.Substring(cmbObjects.SelectedValue.IndexOf("@") + 1);
                        fillDefaultColumns(ref dr, sCurrentDate);
                    }
                }

                #region Report Caption override fields
                if (dsReport.Tables["p_sy_report_att"] != null)
                {
                    DataTable dt = dsReport.Tables["p_sy_report_att"];
                    if (dt != null)
                    {
                        if (dt.Rows.Count == 0)
                        {
                            if (dsReport.Tables["p_sy_report_att"].Rows.Count != lstSelectedFields1.Items.Count)
                                dsReport.Tables["p_sy_report_att"].Rows.Clear();

                            if (dsReport.Tables["p_sy_report_att"].Rows.Count == 0)
                            {
                                #region bin
                                ExecuteVariableQueryAndGetFields();
                                for (int iCount = 0; iCount < lstSelectedFields1.Items.Count; iCount++)
                                {
                                    DataRow drReport = dsReport.Tables["p_sy_report_att"].NewRow();
                                    if (drReport != null)
                                    {
                                        ListItem li = lstSelectedFields1.Items[iCount];

                                        TextBox txtBox = (TextBox)frmObj.FindControl("ContentPlaceHolder3").FindControl("wz_report").FindControl("txt_" + li.Value);
                                        string sCaption = "";
                                        string sId = li.Value;

                                        if (txtBox != null)
                                            sCaption = getCaption(lblReportSrc.Text, sId.Substring(sId.IndexOf("].[") + 3, sId.Length - 1 - (sId.IndexOf("].[") + 3)), txtBox.Text);//;
                                        else
                                            sCaption = li.Text.Substring(li.Text.IndexOf("].[") + 3, li.Text.Length - 1 - (li.Text.IndexOf("].[") + 3));// li.Text;

                                        drReport["rpt_id"] = hf_af_row_id1.Value;
                                        drReport["attrib_id"] = sId.Substring(sId.IndexOf("].[") + 3, sId.Length - 1 - (sId.IndexOf("].[") + 3));
                                        drReport["object_id"] = sId.Substring(1, sId.IndexOf("]") - 1);
                                        if (IsEdit)
                                        {
                                            string sTemp = "";
                                            //DataRow[] drr = GlobalValues.dsAudit.Tables["p_sy_report_att"].Select("object_id='" + drReport["object_id"].ToString() + "' and attrib_id='" + drReport["attrib_id"].ToString() + "'"); //Commanded by 'Imran Gani' on 23/02/2012, to ignore GlobalValues.dsAufit.
                                            DataRow[] drr = dsReport.Tables["p_sy_report_att"].Select("object_id='" + drReport["object_id"].ToString() + "' and attrib_id='" + drReport["attrib_id"].ToString() + "'"); //Added by 'Imran Gani' on 23/02/2012, to avoid GlobalValues.dsAufit.
                                            if (drr.Length > 0)
                                                sTemp = drr[0]["af_row_id"].ToString();
                                            if (sTemp == "") sTemp = SR.getHashKey();
                                            drReport["af_row_id"] = sTemp;
                                        }
                                        else
                                            drReport["af_row_id"] = SR.getHashKey();
                                        drReport["caption"] = sCaption;
                                        drReport["attrib_sequence"] = iCount;

                                        DropDownList dd1 = (DropDownList)frmObj.FindControl("ContentPlaceHolder3").FindControl("wz_report").FindControl("dd_" + li.Value + "_bold");
                                        if (dd1 != null)
                                            drReport["is_bold"] = dd1.Text.ToLower() == "yes" ? "true" : "false";

                                        dd1 = (DropDownList)frmObj.FindControl("ContentPlaceHolder3").FindControl("wz_report").FindControl("dd_" + li.Value + "_wwrap");
                                        if (dd1 != null)
                                            drReport["is_wrap"] = dd1.Text.ToLower() == "yes" ? "true" : "false"; ;

                                        fillDefaultColumns(ref drReport, sCurrentDate);

                                        dsReport.Tables["p_sy_report_att"].Rows.Add(drReport);
                                    }
                                }
                                #endregion
                            }
                        }
                        else
                        {
                            validateSelFields(ref dt);
                            for (int k = 0; k < dt.Rows.Count; k++)
                            {
                                DataRow dr = dt.Rows[k];
                                DataRow[] drF = dsReport.Tables["p_sy_report_att"].Select("af_row_id='" + dr["af_row_id"].ToString() + "'", "attrib_sequence");
                                if (drF.Length == 0)
                                {
                                    DataRow drReport = dsReport.Tables["p_sy_report_att"].NewRow();
                                    drReport["rpt_id"] = hf_af_row_id1.Value;
                                    string sId = dr["attrib_id"].ToString();
                                    drReport["attrib_id"] = sId.Substring(sId.IndexOf("].[") + 3, sId.Length - 1 - (sId.IndexOf("].[") + 3));
                                    drReport["object_id"] = sId.Substring(1, sId.IndexOf("]") - 1);
                                    drReport["caption"] = getCaption(lblReportSrc.Text, sId.Substring(sId.IndexOf("].[") + 3, sId.Length - 1 - (sId.IndexOf("].[") + 3)), dr["caption"].ToString());
                                    drReport["attrib_sequence"] = k;
                                    drReport["is_bold"] = dr["is_bold"].ToString().ToLower() == "yes" ? "true" : "false";
                                    drReport["is_wrap"] = dr["is_wrap"].ToString().ToLower() == "yes" ? "true" : "false"; ;
                                    fillDefaultColumns(ref drReport, sCurrentDate);
                                    dsReport.Tables["p_sy_report_att"].Rows.Add(drReport);
                                }
                                else
                                {
                                    if (drF[0]["af_row_id"].ToString().Trim() == "" || IsEdit == false)
                                        drF[0]["af_row_id"] = SR.getHashKey();
                                    drF[0]["rpt_id"] = hf_af_row_id1.Value;
                                    string sId = dr["attrib_id"].ToString();
                                    if (sId.IndexOf("].[") != -1)
                                    {
                                        drF[0]["attrib_id"] = sId.Substring(sId.IndexOf("].[") + 3, sId.Length - 1 - (sId.IndexOf("].[") + 3));
                                        drF[0]["object_id"] = sId.Substring(1, sId.IndexOf("]") - 1);
                                        drF[0]["caption"] = getCaption(lblReportSrc.Text, sId.Substring(sId.IndexOf("].[") + 3, sId.Length - 1 - (sId.IndexOf("].[") + 3)), dr["caption"].ToString());
                                    }
                                    else
                                        drF[0]["attrib_id"] = sId;
                                    //drF[0]["caption"] = dr["caption"].ToString();
                                    drF[0]["attrib_sequence"] = k;
                                    if (dr["is_bold"].ToString().ToLower() == "yes" || dr["is_bold"].ToString().ToLower() == "no")
                                        drF[0]["is_bold"] = dr["is_bold"].ToString().ToLower() == "yes" ? "true" : "false";
                                    //else if (dr["is_bold"].ToString().ToLower() == "true" || dr["is_bold"].ToString().ToLower() == "false")
                                    //    drF[0]["is_bold"] = dr["is_bold"].ToString().ToLower() == "yes" ? "true" : "false";
                                    if (dr["is_wrap"].ToString().ToLower() == "yes" || dr["is_wrap"].ToString().ToLower() == "no")
                                        drF[0]["is_wrap"] = dr["is_wrap"].ToString().ToLower() == "yes" ? "true" : "false"; ;
                                    fillDefaultColumns(ref drF[0], sCurrentDate);
                                }
                            }
                        }
                    }
                    else
                    {
                        if (dsReport.Tables["p_sy_report_att"].Rows.Count != lstSelectedFields1.Items.Count)
                            dsReport.Tables["p_sy_report_att"].Rows.Clear();

                        if (dsReport.Tables["p_sy_report_att"].Rows.Count == 0)
                        {
                            #region bin
                            ExecuteVariableQueryAndGetFields();
                            for (int iCount = 0; iCount < lstSelectedFields1.Items.Count; iCount++)
                            {
                                DataRow drReport = dsReport.Tables["p_sy_report_att"].NewRow();
                                if (drReport != null)
                                {
                                    ListItem li = lstSelectedFields1.Items[iCount];

                                    TextBox txtBox = (TextBox)frmObj.FindControl("ContentPlaceHolder3").FindControl("wz_report").FindControl("txt_" + li.Value);
                                    string sCaption = "";
                                    string sId = li.Value;

                                    if (txtBox != null)
                                        sCaption = getCaption(lblReportSrc.Text, sId.Substring(sId.IndexOf("].[") + 3, sId.Length - 1 - (sId.IndexOf("].[") + 3)), txtBox.Text);//;
                                    else
                                        sCaption = li.Text.Substring(li.Text.IndexOf("].[") + 3, li.Text.Length - 1 - (li.Text.IndexOf("].[") + 3));// li.Text;

                                    drReport["rpt_id"] = hf_af_row_id1.Value;
                                    drReport["attrib_id"] = sId.Substring(sId.IndexOf("].[") + 3, sId.Length - 1 - (sId.IndexOf("].[") + 3));
                                    drReport["object_id"] = sId.Substring(1, sId.IndexOf("]") - 1);
                                    if (IsEdit)
                                    {
                                        string sTemp = "";
                                        //DataRow[] drr = GlobalValues.dsAudit.Tables["p_sy_report_att"].Select("object_id='" + drReport["object_id"].ToString() + "' and attrib_id='" + drReport["attrib_id"].ToString() + "'"); //Commanded by 'Imran Gani' on 23/02/2012, to ignore GlobalValues.dsAufit.
                                        DataRow[] drr = dsReport.Tables["p_sy_report_att"].Select("object_id='" + drReport["object_id"].ToString() + "' and attrib_id='" + drReport["attrib_id"].ToString() + "'"); //Added by 'Imran Gani' on 23/02/2012, to avoid GlobalValues.dsAufit.
                                        if (drr.Length > 0)
                                            sTemp = drr[0]["af_row_id"].ToString();
                                        if (sTemp == "") sTemp = SR.getHashKey();
                                        drReport["af_row_id"] = sTemp;
                                    }
                                    else
                                        drReport["af_row_id"] = SR.getHashKey();
                                    drReport["caption"] = sCaption;
                                    drReport["attrib_sequence"] = iCount;

                                    DropDownList dd1 = (DropDownList)frmObj.FindControl("ContentPlaceHolder3").FindControl("wz_report").FindControl("dd_" + li.Value + "_bold");
                                    if (dd1 != null)
                                        drReport["is_bold"] = dd1.Text.ToLower() == "yes" ? "true" : "false";

                                    dd1 = (DropDownList)frmObj.FindControl("ContentPlaceHolder3").FindControl("wz_report").FindControl("dd_" + li.Value + "_wwrap");
                                    if (dd1 != null)
                                        drReport["is_wrap"] = dd1.Text.ToLower() == "yes" ? "true" : "false"; ;

                                    fillDefaultColumns(ref drReport, sCurrentDate);

                                    dsReport.Tables["p_sy_report_att"].Rows.Add(drReport);
                                }
                            }
                            #endregion
                        }
                    }
                }
            }
                #endregion

            #region Source Filtering
            // Added by Imran Gani on 20-Jul-2012, for Source Filter.
            if (dsReport.Tables["p_report_source_filter"] != null)
            {
                DataTable dt = dsReport.Tables["p_report_source_filter"];
                for (int k = 0; k < dt.Rows.Count; k++)
                {
                    DataRow dr = dt.Rows[k];
                    if (dr != null)
                    {
                        if (dr["af_row_id"].ToString().Trim() == "" || IsEdit == false)
                            dr["af_row_id"] = SR.getHashKey();
                        dr["rpt_id"] = hf_af_row_id1.Value;
                        fillDefaultColumns(ref dr, sCurrentDate);
                    }
                }
            }
            #endregion

            #region grouping
                ArrayList alKeys = new ArrayList();
            if (dsReport.Tables["p_report_grouping"] != null)
            {
                DataTable dt = dsReport.Tables["p_report_grouping"];
                validateSelGrouping(ref dt, IsEdit);
                if (dt != null)
                {
                    for (int k = 0; k < dt.Rows.Count; k++)
                    {
                        DataRow[] drF = dsReport.Tables["p_report_grouping"].Select("af_row_id='" + dt.Rows[k]["af_row_id"].ToString() + "'");
                        DataRow dr = dt.Rows[k];
                        if (drF.Length == 0)
                        {
                            DataRow drReport = dsReport.Tables["p_report_grouping"].NewRow();
                            drReport["rpt_id"] = hf_af_row_id1.Value;
                            group_af_row_id = SR.getHashKey();
                            alKeys.Add(group_af_row_id);
                            drReport["af_row_id"] = group_af_row_id;

                            string sId = dr["grouping_field"].ToString();
                            if (sId.IndexOf("].[") > -1)
                                sId = sId.Substring(sId.IndexOf("].[") + 3, sId.Length - 1 - (sId.IndexOf("].[") + 3));

                            drReport["grouping_field"] = sId;
                            drReport["grouping_order"] = dr["grouping_order"];
                            drReport["show_header"] = dr["show_header"];
                            drReport["show_subtotal"] = dr["show_subtotal"];
                            drReport["attribute_sequence"] = (k + 1);
                            fillDefaultColumns(ref drReport, sCurrentDate);
                            dsReport.Tables["p_report_grouping"].Rows.Add(drReport);
                        }
                        else
                        {
                            drF[0]["rpt_id"] = hf_af_row_id1.Value;
                            if (dr["af_row_id"].ToString().Trim() == "" || IsEdit == false)
                                dr["af_row_id"] = SR.getHashKey();
                            group_af_row_id = dr["af_row_id"].ToString();
                            alKeys.Add(group_af_row_id);
                            drF[0]["af_row_id"] = group_af_row_id;

                            string sId = dr["grouping_field"].ToString();
                            if (sId.IndexOf("].[") > -1)
                                sId = sId.Substring(sId.IndexOf("].[") + 3, sId.Length - 1 - (sId.IndexOf("].[") + 3));

                            drF[0]["grouping_field"] = sId;
                            drF[0]["grouping_order"] = dr["grouping_order"];
                            drF[0]["show_header"] = dr["show_header"];
                            drF[0]["show_subtotal"] = dr["show_subtotal"];
                            drF[0]["attribute_sequence"] = (k + 1);
                            fillDefaultColumns(ref drF[0], sCurrentDate);
                        }
                    }
                }
            }

            if (dsReport.Tables["p_report_grouping_header"] != null)
            {
                DataTable dt = dsReport.Tables["p_report_grouping_header"];
                validateSelGroupingHdrSub(ref dt, "hdr", "header");
                if (dt != null)
                {
                    for (int k = 0; k < dt.Rows.Count; k++)
                    {
                        DataRow dr = dt.Rows[k];
                        DataRow[] drF = dsReport.Tables["p_report_grouping_header"].Select("af_row_id='" + dt.Rows[k]["af_row_id"].ToString() + "'");
                        if (drF.Length == 0)
                        {
                            DataRow drReport = dsReport.Tables["p_report_grouping_header"].NewRow();
                            drReport["rpt_group_id"] = alKeys[Convert.ToInt32(dr["group_sequence"].ToString()) - 1];
                            drReport["af_row_id"] = SR.getHashKey();

                            string sId = dr["header_field"].ToString();
                            if (sId.IndexOf("].[") > -1)
                                sId = sId.Substring(sId.IndexOf("].[") + 3, sId.Length - 1 - (sId.IndexOf("].[") + 3));

                            drReport["header_field"] = sId;
                            drReport["group_sequence"] = dr["group_sequence"];
                            drReport["field_sequence"] = dr["field_sequence"];
                            fillDefaultColumns(ref drReport, sCurrentDate);
                            dsReport.Tables["p_report_grouping_header"].Rows.Add(drReport);
                        }
                        else
                        {
                            drF[0]["rpt_group_id"] = alKeys[Convert.ToInt32(dr["group_sequence"].ToString()) - 1];
                            if (dr["af_row_id"].ToString().Trim() == "" || IsEdit == false)
                                dr["af_row_id"] = SR.getHashKey();
                            drF[0]["af_row_id"] = dr["af_row_id"];

                            string sId = dr["header_field"].ToString();
                            if (sId.IndexOf("].[") > -1)//implemented during reporting control change
                                sId = sId.Substring(sId.IndexOf("].[") + 3, sId.Length - 1 - (sId.IndexOf("].[") + 3));

                            drF[0]["header_field"] = sId;
                            drF[0]["group_sequence"] = dr["group_sequence"];
                            drF[0]["field_sequence"] = dr["field_sequence"];
                            fillDefaultColumns(ref drF[0], sCurrentDate);
                        }
                    }
                }
            }

            if (dsReport.Tables["p_report_grouping_subtotal"] != null)
            {
                DataTable dt = dsReport.Tables["p_report_grouping_subtotal"];
                validateSelGroupingHdrSub(ref dt, "sub", "subtotal");
                if (dt != null)
                {
                    for (int k = 0; k < dt.Rows.Count; k++)
                    {
                        DataRow dr = dt.Rows[k];
                        DataRow[] drF = dsReport.Tables["p_report_grouping_subtotal"].Select("af_row_id='" + dt.Rows[k]["af_row_id"].ToString() + "'");
                        if (drF.Length == 0)
                        {
                            DataRow drReport = dsReport.Tables["p_report_grouping_subtotal"].NewRow();
                            drReport["rpt_group_id"] = alKeys[Convert.ToInt32(dr["group_sequence"].ToString()) - 1];
                            drReport["af_row_id"] = SR.getHashKey();

                            string sId = dr["subtotal_field"].ToString();
                            if (sId.IndexOf("].[") > -1)//implemented during report control change
                                sId = sId.Substring(sId.IndexOf("].[") + 3, sId.Length - 1 - (sId.IndexOf("].[") + 3));

                            drReport["subtotal_field"] = sId;
                            drReport["group_sequence"] = dr["group_sequence"];
                            drReport["field_sequence"] = dr["field_sequence"];
                            fillDefaultColumns(ref drReport, sCurrentDate);
                            dsReport.Tables["p_report_grouping_subtotal"].Rows.Add(drReport);
                        }
                        else
                        {
                            drF[0]["rpt_group_id"] = alKeys[Convert.ToInt32(dr["group_sequence"].ToString()) - 1];
                            if (dr["af_row_id"].ToString().Trim() == "" || IsEdit == false)
                                dr["af_row_id"] = SR.getHashKey();
                            drF[0]["af_row_id"] = dr["af_row_id"];

                            string sId = dr["subtotal_field"].ToString();
                            if (sId.IndexOf("].[") > -1)
                                sId = sId.Substring(sId.IndexOf("].[") + 3, sId.Length - 1 - (sId.IndexOf("].[") + 3));

                            drF[0]["subtotal_field"] = sId;
                            drF[0]["group_sequence"] = dr["group_sequence"];
                            drF[0]["field_sequence"] = dr["field_sequence"];
                            fillDefaultColumns(ref drF[0], sCurrentDate);
                        }
                    }
                }
            }

            #region commented for phase-1
            //if (dsReport.Tables["p_report_grouping_sort_details"] != null)
            //{
            //    DataTable dt = dsReport.Tables["step3_report_grouping_sort_details"];
            //    if (dt != null)
            //    {
            //        for (int k = 0; k < dt.Rows.Count; k++)
            //        {
            //            DataRow dr = dt.Rows[k];
            //            DataRow[] drF = dsReport.Tables["p_report_grouping_sort_details"].Select("af_row_id='" + dt.Rows[k]["af_row_id"].ToString() + "'");
            //            if (drF.Length == 0)
            //            {
            //                DataRow drReport = dsReport.Tables["p_report_grouping_sort_details"].NewRow();
            //                drReport["rpt_id"] = hf_af_row_id1.Value;
            //                drReport["af_row_id"] = SR.getHashKey();

            //                string sId = dr["sort_detail_field"].ToString();
            //                sId = sId.Substring(sId.IndexOf("].[") + 3, sId.Length - 1 - (sId.IndexOf("].[") + 3));

            //                drReport["sort_detail_field"] = sId;
            //                drReport["sort_detail_order"] = dr["sort_detail_order"];
            //                drReport["attribute_sequence"] = k+1;
            //                fillDefaultColumns(ref drReport, sCurrentDate);
            //                dsReport.Tables["p_report_grouping_sort_details"].Rows.Add(drReport);
            //            }
            //            else
            //            {
            //                drF[0]["rpt_id"] = hf_af_row_id1.Value;
            //                drF[0]["af_row_id"] = dr["af_row_id"];

            //                string sId = dr["sort_detail_field"].ToString();
            //                sId = sId.Substring(sId.IndexOf("].[") + 3, sId.Length - 1 - (sId.IndexOf("].[") + 3));

            //                drF[0]["sort_detail_field"] = sId;
            //                drF[0]["sort_detail_order"] = dr["sort_detail_order"];
            //                drF[0]["attribute_sequence"] = k+1;
            //                fillDefaultColumns(ref drF[0], sCurrentDate);
            //            }                            
            //        }
            //    }
            //}
            #endregion

            if (dsReport.Tables["p_report_grouping_grand_total"] != null)
            {
                DataTable dt = dsReport.Tables["p_report_grouping_grand_total"];
                if (dt != null)
                {
                    for (int k = 0; k < dt.Rows.Count; k++)
                    {
                        DataRow dr = dt.Rows[k];
                        DataRow[] drF = dsReport.Tables["p_report_grouping_grand_total"].Select("af_row_id='" + dt.Rows[k]["af_row_id"].ToString() + "'");
                        if (drF.Length == 0)
                        {
                            DataRow drReport = dsReport.Tables["p_report_grouping_grand_total"].NewRow();
                            drReport["rpt_id"] = hf_af_row_id1.Value;
                            drReport["af_row_id"] = SR.getHashKey();

                            string sId = dr["grand_total_field"].ToString();
                            if (sId.IndexOf("].[") > -1)
                                sId = sId.Substring(sId.IndexOf("].[") + 3, sId.Length - 1 - (sId.IndexOf("].[") + 3));

                            drReport["grand_total_field"] = sId;
                            drReport["attribute_sequence"] = dr["attribute_sequence"];
                            fillDefaultColumns(ref drReport, sCurrentDate);
                            dsReport.Tables["p_report_grouping_grand_total"].Rows.Add(drReport);
                        }
                        else
                        {
                            drF[0]["rpt_id"] = hf_af_row_id1.Value;
                            if (dr["af_row_id"].ToString().Trim() == "" || IsEdit == false)
                                dr["af_row_id"] = SR.getHashKey();
                            drF[0]["af_row_id"] = dr["af_row_id"];

                            string sId = dr["grand_total_field"].ToString();
                            if (sId.IndexOf("].[") > -1)
                                sId = sId.Substring(sId.IndexOf("].[") + 3, sId.Length - 1 - (sId.IndexOf("].[") + 3));

                            drF[0]["grand_total_field"] = sId;
                            drF[0]["attribute_sequence"] = dr["attribute_sequence"];
                            fillDefaultColumns(ref drF[0], sCurrentDate);
                        }
                    }
                }
            }
            #endregion

            #region header_footer
            if (dsReport.Tables["p_report_header_footer"] != null)
            {
                DataTable dt = dsReport.Tables["p_report_header_footer"];
                if (dt != null)
                {
                    for (int k = 0; k < dt.Rows.Count; k++)
                    {
                        DataRow dr = dt.Rows[k];
                        DataRow[] drF = dsReport.Tables["p_report_header_footer"].Select("af_row_id='" + dt.Rows[k]["af_row_id"].ToString() + "'");
                        if (drF.Length == 0)
                        {
                            DataRow drReport = dsReport.Tables["p_report_header_footer"].NewRow();
                            drReport["rpt_id"] = hf_af_row_id1.Value;
                            drReport["af_row_id"] = SR.getHashKey();
                            drReport["rpt_logo"] = chkDisplayLogo.Checked.ToString();
                            drReport["rpt_head_text"] = txtHeaderText.Text;
                            drReport["rpt_foot_text"] = txtFooterText.Text;
                            drReport["rpt_page_no"] = chkDisplayPageNum.Checked.ToString();
                            drReport["rpt_date"] = chkDisplayDate.Checked.ToString();
                            drReport["rpt_title"] = txtRepTitle.Text;
                            fillDefaultColumns(ref drReport, sCurrentDate);
                            dsReport.Tables["p_report_header_footer"].Rows.Add(drReport);
                        }
                        else
                        {
                            drF[0]["rpt_id"] = hf_af_row_id1.Value;
                            if (dr["af_row_id"].ToString().Trim() == "" || IsEdit == false)
                                dr["af_row_id"] = SR.getHashKey();
                            drF[0]["af_row_id"] = dr["af_row_id"];
                            drF[0]["rpt_logo"] = chkDisplayLogo.Checked.ToString();
                            drF[0]["rpt_head_text"] = txtHeaderText.Text;
                            drF[0]["rpt_foot_text"] = txtFooterText.Text;
                            drF[0]["rpt_page_no"] = chkDisplayPageNum.Checked.ToString();
                            drF[0]["rpt_date"] = chkDisplayDate.Checked.ToString();
                            drF[0]["rpt_title"] = txtRepTitle.Text;
                            fillDefaultColumns(ref drF[0], sCurrentDate);
                        }
                    }
                }
            }
            #endregion
        }

        catch (Exception ex)
        {
            bReturn = false;
            LogWriter.WriteLog("fillInputData : Error : " + ex.Message);
        }
        return bReturn;
    }
    #endregion
    //    #region working function
//    private bool fillInputData(ref DataSet dsReport)
//    {
//        string group_af_row_id = "";
//        bool bReturn = true;
//                #region Base Data
//        try
//        {
//            HtmlForm frmObj = (HtmlForm)this.Master.FindControl("Form1");
//            HtmlTable htProperties = (HtmlTable)frmObj.FindControl("ContentPlaceHolder3").FindControl("wz_report").FindControl("tblproperties");
//            ScreenReader SR = new ScreenReader();
//            if (htProperties != null)
//            {
//                string sPageSetId = m_PageSetId;
//                string sReportId = "";
//                #region MyRegion
//                //if (dsPageInfo == null)
//                //{
//                //    PageInfoLoad objPIL = new PageInfoLoad();
//                //    dsPageInfo = objPIL.GetPageSetPageCtrlInfo(sPageSetId);
//                //} 
//                #endregion

//                //if (dsInputInfo == null)
//                //{

//                //getInputDataSet(ref dsInputInfo);
//                ScreenReader objSR = new ScreenReader();
//                //#region commented and customised for Control change
//               // dsReport = new DataSet();
//                objSR.CreatePageDataTable(dsReport, dsPageInfo.Tables["Page"], dsPageInfo.Tables["PageCtrl"]);
//                //DataSet dsTemp = new DataSet();
//                //objSR.CreatePageDataTable(dsTemp, dsPageInfo.Tables["Page"], dsPageInfo.Tables["PageCtrl"]);
//                //if ((dsReport.Tables["p_sy_report"] != null) && (dsTemp.Tables["p_sy_report"] != null))
//                //{
//                //    dsReport.Tables.Remove("p_sy_report");
//                //    dsReport.Tables.Add(dsTemp.Tables["p_sy_report"].Copy());
//                //}
//                //if ((dsReport.Tables["p_sy_report_obj"] != null) && (dsTemp.Tables["p_sy_report_obj"] != null))
//                //{
//                //    dsReport.Tables.Remove("p_sy_report_obj");
//                //    dsReport.Tables.Add(dsTemp.Tables["p_sy_report_obj"].Copy());
//                //}
//                //if ((dsReport.Tables["p_sy_report_att"] != null) && (dsTemp.Tables["p_sy_report_att"] != null))
//                //{
//                //    dsReport.Tables.Remove("p_sy_report_att");
//                //    dsReport.Tables.Add(dsTemp.Tables["p_sy_report_att"].Copy());
//                //}
//                //#endregion
//               // collect_step_values(2);
//                sReportId = hdd.GetColumnValue("Select max(rpt_id) from sy_report");
//                if (!IsEdit)
//                {
//                    if (sReportId == "")
//                        sReportId = "1";
//                    else
//                        sReportId = Convert.ToString(Convert.ToInt16(sReportId) + 1);
//                }
//                else
//                    sReportId = m_Report_id;

//                string sCurrentDate = DateTime.Now.ToString();

//                if (dsReport.Tables["p_sy_report"] != null)
//                {
//                    DataRow drReport = dsReport.Tables["p_sy_report"].NewRow();
//                    if (drReport != null)
//                    {
//                        drReport["af_row_id"] =  hf_af_row_id1.Value;
//                        drReport["rpt_id"] = sReportId;
//                        drReport["rpt_name"] = txtRepName.Text.Trim();
//                        drReport["rpt_desc"] = txtReportDesc.Text.Trim();
//                        drReport["rpt_type"] = "Tabular";
//                        //if (rbTabular.Checked)
//                        //    drReport["rpt_type"] = rbTabular.Text;
//                        //else if (rbMatrix.Checked)
//                        //    drReport["rpt_type"] = rbMatrix.Text;
//                        //else if (rbMasterDetail.Checked)
//                        //    drReport["rpt_type"] = rbMasterDetail.Text;
//                        //drReport["created_date"] = DateTime.Now();
//                        //if (rbPredefinedObjects.Checked)
//                        //    drReport["rpt_base_object"] = "true";
//                        //else
//                        //    drReport["rpt_base_object"] = "false";
//                        drReport["rpt_base_object"] = lblReportSrc.Text;
//                        fillDefaultColumns(ref drReport, sCurrentDate);
//                    }
//                    dsReport.Tables["p_sy_report"].Rows.Add(drReport);
//                }

//                if (dsReport.Tables["p_sy_report_obj"] != null)
//                {
//                    DataRow drReport = dsReport.Tables["p_sy_report_obj"].NewRow();
//                    if (drReport != null)
//                    {
//                        if (IsEdit)
//                        {
//                            string sTemp = GlobalValues.dsAudit.Tables["p_sy_report_obj"].Rows[0]["af_row_id"].ToString();
//                            if (sTemp == "") sTemp = SR.getHashKey();
//                            drReport["af_row_id"] = sTemp;
//                        }
//                        else
//                            drReport["af_row_id"] = SR.getHashKey();
//                        drReport["rpt_id"] = hf_af_row_id1.Value;
//                        drReport["object_id"] = cmbObjects.SelectedValue.Substring(cmbObjects.SelectedValue.IndexOf('@') + 1);
//                        //drReport["created_date"] = DateTime.Now();

//                        fillDefaultColumns(ref drReport, sCurrentDate);
//                    }
//                    dsReport.Tables["p_sy_report_obj"].Rows.Add(drReport);
//                }

//                if (dsReport.Tables["p_sy_report_att"] != null)
//                {
//                    string sSqlObjID = "Select af_row_id from sy_obj where object_id = '" + cmbObjects.SelectedValue.Substring(cmbObjects.SelectedValue.IndexOf('@') + 1) + "'";
//                    string sSqlColName = "Select attrib_id,attrib_name from sy_obj_att where object_id = '" + hdd.GetColumnValue(sSqlObjID).Trim() + "'";
//                    //string sSqlObjID = "Select attrib_id,attrib_name from sy_obj_att where object_id = '" + cmbObjects.SelectedValue.Substring(cmbObjects.SelectedValue.IndexOf('@') + 1) + "'";

//                    DataTable dtColNames = hdd.GetDataTable(sSqlColName);

//                    if(dsReport.Tables["p_sy_report_att"].Columns["attrib_name"]==null)
//                    {
//                        DataColumn dCol = new DataColumn("attrib_name");
//                        dsReport.Tables["p_sy_report_att"].Columns.Add(dCol);
//                    }


//                    ExecuteVariableQueryAndGetFields();
//                    for (int iCount = 0; iCount < lstSelectedFields1.Items.Count; iCount++)
//                    {
//                        DataRow drReport = dsReport.Tables["p_sy_report_att"].NewRow();
//                        if (drReport != null)
//                        {
//                            ListItem li = lstSelectedFields1.Items[iCount];

//                            TextBox txtBox = (TextBox)frmObj.FindControl("ContentPlaceHolder3").FindControl("wz_report").FindControl("txt_" + li.Value);
//                            string sCaption = "";
//                            if (txtBox != null)
//                                sCaption = txtBox.Text;
//                            else
//                                sCaption = li.Text.Substring(li.Text.IndexOf("].[") + 3, li.Text.Length - 1 - (li.Text.IndexOf("].[") + 3));// li.Text;
//                            string sId = li.Value;

//                            drReport["rpt_id"] = hf_af_row_id1.Value;
//                            drReport["attrib_id"] = sId.Substring(sId.IndexOf("].[") + 3, sId.Length - 1 - (sId.IndexOf("].[") + 3));
//                            //drReport["attrib_id"] = li.Text;
//                            drReport["object_id"] = sId.Substring(1, sId.IndexOf("]") - 1);
//                            DataRow[] drArr = dtColNames.Select("attrib_name='" + li.Text.Substring(li.Text.IndexOf("].[") + 3, li.Text.Length - 1 - (li.Text.IndexOf("].[") + 3)) + "'");
//                            drReport["attrib_name"] = drArr[0]["attrib_id"].ToString();
//                            if (IsEdit)
//                            {
//                                string sTemp = "";
//                                DataRow[] drr = GlobalValues.dsAudit.Tables["p_sy_report_att"].Select("object_id='" + drReport["object_id"].ToString() + "' and attrib_id='" + drReport["attrib_id"].ToString() + "'");
//                                if (drr.Length > 0)
//                                    sTemp = drr[0]["af_row_id"].ToString();
//                                if (sTemp == "") sTemp = SR.getHashKey();
//                                drReport["af_row_id"] = sTemp;
//                            }
//                            else
//                                drReport["af_row_id"] = SR.getHashKey();
//                            drReport["caption"] = sCaption;
//                            drReport["attrib_sequence"] = iCount;

//                            fillDefaultColumns(ref drReport, sCurrentDate);

//                            dsReport.Tables["p_sy_report_att"].Rows.Add(drReport);
//                        }
//                    }
//                }
//#endregion

//                #region grouping
//                ArrayList alKeys = new ArrayList();
                
                



//                if (dsReport.Tables["p_report_grouping"] != null)
//                {
//                    //Missing columns added for control changed
//                    if (dsReport.Tables["p_report_grouping"].Columns["rpt_id"] == null)
//                    {
//                        dsReport.Tables["p_report_grouping"].Columns.Add(new DataColumn("rpt_id"));
//                    }
//                    if (dsReport.Tables["p_report_grouping"].Columns["created_by"] == null)
//                    {
//                        dsReport.Tables["p_report_grouping"].Columns.Add(new DataColumn("created_by"));
//                    }
//                    if (dsReport.Tables["p_report_grouping"].Columns["owner_id"] == null)
//                    {
//                        dsReport.Tables["p_report_grouping"].Columns.Add(new DataColumn("owner_id"));
//                    }
//                    if (dsReport.Tables["p_report_grouping"].Columns["created_at"] == null)
//                    {
//                        dsReport.Tables["p_report_grouping"].Columns.Add(new DataColumn("created_at"));
//                    }
//                    if (dsReport.Tables["p_report_grouping"].Columns["modified_by"] == null)
//                    {
//                        dsReport.Tables["p_report_grouping"].Columns.Add(new DataColumn("modified_by"));
//                    }
//                    if (dsReport.Tables["p_report_grouping"].Columns["modified_at"] == null)
//                    {
//                        dsReport.Tables["p_report_grouping"].Columns.Add(new DataColumn("modified_at"));
//                    }

                    



//                    DataTable dt = dsReport.Tables["p_report_grouping"];
//                    validateSelGrouping(ref dt, IsEdit);
//                    if (dt != null)
//                    {
//                        for (int k = 0; k < dt.Rows.Count; k++)
//                        {
//                            DataRow[] drF = dsReport.Tables["p_report_grouping"].Select("af_row_id='" + dt.Rows[k]["af_row_id"].ToString() + "'");
//                            DataRow dr = dt.Rows[k];
//                            if (drF.Length == 0)
//                            {
//                                DataRow drReport = dsReport.Tables["p_report_grouping"].NewRow();
//                                drReport["rpt_id"] = hf_af_row_id1.Value;
//                                group_af_row_id = SR.getHashKey();
//                                alKeys.Add(group_af_row_id);
//                                drReport["af_row_id"] = group_af_row_id;

//                                string sId = dr["grouping_field"].ToString();
//                                sId = sId.Substring(sId.IndexOf("].[") + 3, sId.Length - 1 - (sId.IndexOf("].[") + 3));

//                                drReport["grouping_field"] = sId;
//                                drReport["grouping_order"] = dr["grouping_order"];
//                                drReport["show_header"] = dr["show_header"];
//                                drReport["show_subtotal"] = dr["show_subtotal"];
//                                drReport["attribute_sequence"] = (k + 1);
//                                fillDefaultColumns(ref drReport, sCurrentDate);
//                                dsReport.Tables["p_report_grouping"].Rows.Add(drReport);
//                            }
//                            else
//                            {
//                                drF[0]["rpt_id"] = hf_af_row_id1.Value;
//                                if (dr["af_row_id"].ToString().Trim() == "" || IsEdit == false)
//                                    dr["af_row_id"] = SR.getHashKey();
//                                group_af_row_id = dr["af_row_id"].ToString();
//                                alKeys.Add(group_af_row_id);
//                                drF[0]["af_row_id"] = group_af_row_id;

//                                string sId = dr["grouping_field"].ToString();
//                                sId = sId.Substring(sId.IndexOf("].[") + 3, sId.Length - 1 - (sId.IndexOf("].[") + 3));

//                                drF[0]["grouping_field"] = sId;
//                                drF[0]["grouping_order"] = dr["grouping_order"];
//                                drF[0]["show_header"] = dr["show_header"];
//                                drF[0]["show_subtotal"] = dr["show_subtotal"];
//                                drF[0]["attribute_sequence"] = (k + 1);
//                                fillDefaultColumns(ref drF[0], sCurrentDate);
//                            }
//                        }
//                    }
//                }

//                if (dsReport.Tables["p_report_grouping_header"] != null)
//                {
//                    //Missing columns added for control changed
//                    if (dsReport.Tables["p_report_grouping_header"].Columns["rpt_id"] == null)
//                    {
//                        dsReport.Tables["p_report_grouping_header"].Columns.Add(new DataColumn("rpt_id"));
//                    }
//                    if (dsReport.Tables["p_report_grouping_header"].Columns["created_by"] == null)
//                    {
//                        dsReport.Tables["p_report_grouping_header"].Columns.Add(new DataColumn("created_by"));
//                    }
//                    if (dsReport.Tables["p_report_grouping_header"].Columns["owner_id"] == null)
//                    {
//                        dsReport.Tables["p_report_grouping_header"].Columns.Add(new DataColumn("owner_id"));
//                    }
//                    if (dsReport.Tables["p_report_grouping_header"].Columns["created_at"] == null)
//                    {
//                        dsReport.Tables["p_report_grouping_header"].Columns.Add(new DataColumn("created_at"));
//                    }
//                    if (dsReport.Tables["p_report_grouping_header"].Columns["modified_by"] == null)
//                    {
//                        dsReport.Tables["p_report_grouping_header"].Columns.Add(new DataColumn("modified_by"));
//                    }
//                    if (dsReport.Tables["p_report_grouping_header"].Columns["modified_at"] == null)
//                    {
//                        dsReport.Tables["p_report_grouping_header"].Columns.Add(new DataColumn("modified_at"));
//                    }




//                    DataTable dt = dsReport.Tables["p_report_grouping_header"];
//                    validateSelGroupingHdrSub(ref dt, "hdr", "header");
//                    if (dt != null)
//                    {
//                        for (int k = 0; k < dt.Rows.Count; k++)
//                        {
//                            DataRow dr = dt.Rows[k];
//                            DataRow[] drF = dsReport.Tables["p_report_grouping_header"].Select("af_row_id='" + dt.Rows[k]["af_row_id"].ToString() + "'");
//                            if (drF.Length == 0)
//                            {
//                                DataRow drReport = dsReport.Tables["p_report_grouping_header"].NewRow();
//                                drReport["rpt_group_id"] = alKeys[Convert.ToInt32(dr["group_sequence"].ToString()) - 1];
//                                drReport["af_row_id"] = SR.getHashKey();

//                                string sId = dr["header_field"].ToString();
//                                sId = sId.Substring(sId.IndexOf("].[") + 3, sId.Length - 1 - (sId.IndexOf("].[") + 3));

//                                drReport["header_field"] = sId;
//                                drReport["group_sequence"] = dr["group_sequence"];
//                                drReport["field_sequence"] = dr["field_sequence"];
//                                fillDefaultColumns(ref drReport, sCurrentDate);
//                                dsReport.Tables["p_report_grouping_header"].Rows.Add(drReport);
//                            }
//                            else
//                            {
//                                drF[0]["rpt_group_id"] = alKeys[Convert.ToInt32(dr["group_sequence"].ToString()) - 1];
//                                if (dr["af_row_id"].ToString().Trim() == "" || IsEdit == false)
//                                    dr["af_row_id"] = SR.getHashKey();
//                                drF[0]["af_row_id"] = dr["af_row_id"];

//                                string sId = dr["header_field"].ToString();
//                                sId = sId.Substring(sId.IndexOf("].[") + 3, sId.Length - 1 - (sId.IndexOf("].[") + 3));

//                                drF[0]["header_field"] = sId;
//                                drF[0]["group_sequence"] = dr["group_sequence"];
//                                drF[0]["field_sequence"] = dr["field_sequence"];
//                                fillDefaultColumns(ref drF[0], sCurrentDate);
//                            }
//                        }
//                    }
//                }

//                if (dsReport.Tables["p_report_grouping_subtotal"] != null)
//                {
//                    //Missing columns added for control changed
//                    if (dsReport.Tables["p_report_grouping_subtotal"].Columns["rpt_id"] == null)
//                    {
//                        dsReport.Tables["p_report_grouping_subtotal"].Columns.Add(new DataColumn("rpt_id"));
//                    }
//                    if (dsReport.Tables["p_report_grouping_subtotal"].Columns["created_by"] == null)
//                    {
//                        dsReport.Tables["p_report_grouping_subtotal"].Columns.Add(new DataColumn("created_by"));
//                    }
//                    if (dsReport.Tables["p_report_grouping_subtotal"].Columns["owner_id"] == null)
//                    {
//                        dsReport.Tables["p_report_grouping_subtotal"].Columns.Add(new DataColumn("owner_id"));
//                    }
//                    if (dsReport.Tables["p_report_grouping_subtotal"].Columns["created_at"] == null)
//                    {
//                        dsReport.Tables["p_report_grouping_subtotal"].Columns.Add(new DataColumn("created_at"));
//                    }
//                    if (dsReport.Tables["p_report_grouping_subtotal"].Columns["modified_by"] == null)
//                    {
//                        dsReport.Tables["p_report_grouping_subtotal"].Columns.Add(new DataColumn("modified_by"));
//                    }
//                    if (dsReport.Tables["p_report_grouping_subtotal"].Columns["modified_at"] == null)
//                    {
//                        dsReport.Tables["p_report_grouping_subtotal"].Columns.Add(new DataColumn("modified_at"));
//                    }




//                    DataTable dt = dsReport.Tables["p_report_grouping_subtotal"];
//                    validateSelGroupingHdrSub(ref dt, "sub", "subtotal");
//                    if (dt != null)
//                    {
//                        for (int k = 0; k < dt.Rows.Count; k++)
//                        {
//                            DataRow dr = dt.Rows[k];
//                            DataRow[] drF = dsReport.Tables["p_report_grouping_subtotal"].Select("af_row_id='" + dt.Rows[k]["af_row_id"].ToString() + "'");
//                            if (drF.Length == 0)
//                            {
//                                DataRow drReport = dsReport.Tables["p_report_grouping_subtotal"].NewRow();
//                                drReport["rpt_group_id"] = alKeys[Convert.ToInt32(dr["group_sequence"].ToString()) - 1];
//                                drReport["af_row_id"] = SR.getHashKey();

//                                string sId = dr["subtotal_field"].ToString();
//                                sId = sId.Substring(sId.IndexOf("].[") + 3, sId.Length - 1 - (sId.IndexOf("].[") + 3));

//                                drReport["subtotal_field"] = sId;
//                                drReport["group_sequence"] = dr["group_sequence"];
//                                drReport["field_sequence"] = dr["field_sequence"];
//                                fillDefaultColumns(ref drReport, sCurrentDate);
//                                dsReport.Tables["p_report_grouping_subtotal"].Rows.Add(drReport);
//                            }
//                            else
//                            {
//                                drF[0]["rpt_group_id"] = alKeys[Convert.ToInt32(dr["group_sequence"].ToString()) - 1];
//                                if (dr["af_row_id"].ToString().Trim() == "" || IsEdit == false)
//                                    dr["af_row_id"] = SR.getHashKey();
//                                drF[0]["af_row_id"] = dr["af_row_id"];

//                                string sId = dr["subtotal_field"].ToString();
//                                sId = sId.Substring(sId.IndexOf("].[") + 3, sId.Length - 1 - (sId.IndexOf("].[") + 3));

//                                drF[0]["subtotal_field"] = sId;
//                                drF[0]["group_sequence"] = dr["group_sequence"];
//                                drF[0]["field_sequence"] = dr["field_sequence"];
//                                fillDefaultColumns(ref drF[0], sCurrentDate);
//                            }
//                        }
//                    }
//                }

//                #region commented for phase-1
//                //if (dsReport.Tables["p_report_grouping_sort_details"] != null)
//                //{
//                //    DataTable dt = dsReport.Tables["step3_report_grouping_sort_details"];
//                //    if (dt != null)
//                //    {
//                //        for (int k = 0; k < dt.Rows.Count; k++)
//                //        {
//                //            DataRow dr = dt.Rows[k];
//                //            DataRow[] drF = dsReport.Tables["p_report_grouping_sort_details"].Select("af_row_id='" + dt.Rows[k]["af_row_id"].ToString() + "'");
//                //            if (drF.Length == 0)
//                //            {
//                //                DataRow drReport = dsReport.Tables["p_report_grouping_sort_details"].NewRow();
//                //                drReport["rpt_id"] = hf_af_row_id1.Value;
//                //                drReport["af_row_id"] = SR.getHashKey();

//                //                string sId = dr["sort_detail_field"].ToString();
//                //                sId = sId.Substring(sId.IndexOf("].[") + 3, sId.Length - 1 - (sId.IndexOf("].[") + 3));

//                //                drReport["sort_detail_field"] = sId;
//                //                drReport["sort_detail_order"] = dr["sort_detail_order"];
//                //                drReport["attribute_sequence"] = k+1;
//                //                fillDefaultColumns(ref drReport, sCurrentDate);
//                //                dsReport.Tables["p_report_grouping_sort_details"].Rows.Add(drReport);
//                //            }
//                //            else
//                //            {
//                //                drF[0]["rpt_id"] = hf_af_row_id1.Value;
//                //                drF[0]["af_row_id"] = dr["af_row_id"];

//                //                string sId = dr["sort_detail_field"].ToString();
//                //                sId = sId.Substring(sId.IndexOf("].[") + 3, sId.Length - 1 - (sId.IndexOf("].[") + 3));

//                //                drF[0]["sort_detail_field"] = sId;
//                //                drF[0]["sort_detail_order"] = dr["sort_detail_order"];
//                //                drF[0]["attribute_sequence"] = k+1;
//                //                fillDefaultColumns(ref drF[0], sCurrentDate);
//                //            }                            
//                //        }
//                //    }
//                //}
//                #endregion

//                if (dsReport.Tables["p_report_grouping_grand_total"] != null)
//                {
//                    //Missing columns added for control changed
//                    if (dsReport.Tables["p_report_grouping_grand_total"].Columns["rpt_id"] == null)
//                    {
//                        dsReport.Tables["p_report_grouping_grand_total"].Columns.Add(new DataColumn("rpt_id"));
//                    }
//                    if (dsReport.Tables["p_report_grouping_grand_total"].Columns["created_by"] == null)
//                    {
//                        dsReport.Tables["p_report_grouping_grand_total"].Columns.Add(new DataColumn("created_by"));
//                    }
//                    if (dsReport.Tables["p_report_grouping_grand_total"].Columns["owner_id"] == null)
//                    {
//                        dsReport.Tables["p_report_grouping_grand_total"].Columns.Add(new DataColumn("owner_id"));
//                    }
//                    if (dsReport.Tables["p_report_grouping_grand_total"].Columns["created_at"] == null)
//                    {
//                        dsReport.Tables["p_report_grouping_grand_total"].Columns.Add(new DataColumn("created_at"));
//                    }
//                    if (dsReport.Tables["p_report_grouping_grand_total"].Columns["modified_by"] == null)
//                    {
//                        dsReport.Tables["p_report_grouping_grand_total"].Columns.Add(new DataColumn("modified_by"));
//                    }
//                    if (dsReport.Tables["p_report_grouping_grand_total"].Columns["modified_at"] == null)
//                    {
//                        dsReport.Tables["p_report_grouping_grand_total"].Columns.Add(new DataColumn("modified_at"));
//                    }








//                    DataTable dt = dsReport.Tables["p_report_grouping_grand_total"];
//                    if (dt != null)
//                    {
//                        for (int k = 0; k < dt.Rows.Count; k++)
//                        {
//                            DataRow dr = dt.Rows[k];
//                            DataRow[] drF = dsReport.Tables["p_report_grouping_grand_total"].Select("af_row_id='" + dt.Rows[k]["af_row_id"].ToString() + "'");
//                            if (drF.Length == 0)
//                            {
//                                DataRow drReport = dsReport.Tables["p_report_grouping_grand_total"].NewRow();
//                                drReport["rpt_id"] = hf_af_row_id1.Value;
//                                drReport["af_row_id"] = SR.getHashKey();

//                                string sId = dr["grand_total_field"].ToString();
//                                sId = sId.Substring(sId.IndexOf("].[") + 3, sId.Length - 1 - (sId.IndexOf("].[") + 3));

//                                drReport["grand_total_field"] = sId;
//                                drReport["attribute_sequence"] = dr["attribute_sequence"];
//                                fillDefaultColumns(ref drReport, sCurrentDate);
//                                dsReport.Tables["p_report_grouping_grand_total"].Rows.Add(drReport);
//                            }
//                            else
//                            {
//                                drF[0]["rpt_id"] = hf_af_row_id1.Value;
//                                if (dr["af_row_id"].ToString().Trim() == "" || IsEdit == false)
//                                    dr["af_row_id"] = SR.getHashKey();
//                                drF[0]["af_row_id"] = dr["af_row_id"];

//                                string sId = dr["grand_total_field"].ToString();
//                                sId = sId.Substring(sId.IndexOf("].[") + 3, sId.Length - 1 - (sId.IndexOf("].[") + 3));

//                                drF[0]["grand_total_field"] = sId;
//                                drF[0]["attribute_sequence"] = dr["attribute_sequence"];
//                                fillDefaultColumns(ref drF[0], sCurrentDate);
//                            }
//                        }
//                    }
//                }
//                #endregion

//                #region header_footer
//                if (dsReport.Tables["p_report_header_footer"] != null)
//                {
//                    //Missing columns added for control changed
//                    if (dsReport.Tables["p_report_header_footer"].Columns["rpt_id"] == null)
//                    {
//                        dsReport.Tables["p_report_header_footer"].Columns.Add(new DataColumn("rpt_id"));
//                    }
//                    if (dsReport.Tables["p_report_header_footer"].Columns["created_by"] == null)
//                    {
//                        dsReport.Tables["p_report_header_footer"].Columns.Add(new DataColumn("created_by"));
//                    }
//                    if (dsReport.Tables["p_report_header_footer"].Columns["owner_id"] == null)
//                    {
//                        dsReport.Tables["p_report_header_footer"].Columns.Add(new DataColumn("owner_id"));
//                    }
//                    if (dsReport.Tables["p_report_header_footer"].Columns["created_at"] == null)
//                    {
//                        dsReport.Tables["p_report_header_footer"].Columns.Add(new DataColumn("created_at"));
//                    }
//                    if (dsReport.Tables["p_report_header_footer"].Columns["modified_by"] == null)
//                    {
//                        dsReport.Tables["p_report_header_footer"].Columns.Add(new DataColumn("modified_by"));
//                    }
//                    if (dsReport.Tables["p_report_header_footer"].Columns["modified_at"] == null)
//                    {
//                        dsReport.Tables["p_report_header_footer"].Columns.Add(new DataColumn("modified_at"));
//                    }



//                    DataTable dt = dsReport.Tables["p_report_header_footer"];
//                    if (dt != null)
//                    {
//                        for (int k = 0; k < dt.Rows.Count; k++)
//                        {
//                            DataRow dr = dt.Rows[k];
//                            DataRow[] drF = dsReport.Tables["p_report_header_footer"].Select("af_row_id='" + dt.Rows[k]["af_row_id"].ToString() + "'");
//                            if (drF.Length == 0)
//                            {
//                                DataRow drReport = dsReport.Tables["p_report_header_footer"].NewRow();
//                                drReport["rpt_id"] = hf_af_row_id1.Value;
//                                drReport["af_row_id"] = SR.getHashKey();
//                                drReport["rpt_logo"] = chkDisplayLogo.Checked.ToString();
//                                drReport["rpt_head_text"] = txtHeaderText.Text;
//                                drReport["rpt_foot_text"] = txtFooterText.Text;
//                                drReport["rpt_page_no"] = chkDisplayPageNum.Checked.ToString();
//                                drReport["rpt_date"] = chkDisplayDate.Checked.ToString();
//                                drReport["rpt_title"] = txtRepTitle.Text;
//                                fillDefaultColumns(ref drReport, sCurrentDate);
//                                dsReport.Tables["p_report_header_footer"].Rows.Add(drReport);
//                            }
//                            else
//                            {
//                                drF[0]["rpt_id"] = hf_af_row_id1.Value;
//                                if (dr["af_row_id"].ToString().Trim() == "" || IsEdit == false)
//                                    dr["af_row_id"] = SR.getHashKey();
//                                drF[0]["af_row_id"] = dr["af_row_id"];
//                                drF[0]["rpt_logo"] = chkDisplayLogo.Checked.ToString();
//                                drF[0]["rpt_head_text"] = txtHeaderText.Text;
//                                drF[0]["rpt_foot_text"] = txtFooterText.Text;
//                                drF[0]["rpt_page_no"] = chkDisplayPageNum.Checked.ToString();
//                                drF[0]["rpt_date"] = chkDisplayDate.Checked.ToString();
//                                drF[0]["rpt_title"] = txtRepTitle.Text;
//                                fillDefaultColumns(ref drF[0], sCurrentDate);
//                            }
//                        }
//                    }
//                }
//                #endregion
//            }
//        }

//        catch (Exception ex)
//        {
//            bReturn = false;
//            LogWriter.WriteLog(this.Title + " : Error : " + ex.Message);
//        }
//        return bReturn;
//    }
//    #endregion
    private string fillGroupingValues(DataSet dsReport, string tableName, string fieldValue, string fieldName, bool isValue, string dsFieldName)
    {
        string retVal = "0";
        try
        {
            DataRow[] drF = dsReport.Tables[tableName].Select("" + fieldName + "='" + fieldValue + "'");
            if (isValue)
            {
                if (drF == null)
                    retVal = "";
                else
                {
                    if (drF[0][dsFieldName].ToString().Trim() != "")
                        retVal = drF[0][dsFieldName].ToString().Substring(0, 3);
                    else
                        retVal = "";
                }
            }
            else
            {
                if (drF == null)
                    retVal = "0";
                else
                    retVal = drF[0]["attribute_sequence"].ToString();
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("fillGroupingValues : Error : " + ex.Message);
        }
        return retVal;
    }

    private void ExecuteVariableQueryAndGetFields()
    {
        try
        {
            if (dsReport.Tables["p_sy_report"].Rows[0]["rpt_base_object"].ToString().ToLower() == "sql")
            {
                DataRow dr = hdd.GetTableRow("select * from sy_report_sql where report_base_id=" + cmbObjects.SelectedItem.Value);
                if (dr != null)
                {
                    lblReportSrc.Text = dr["report_base_desc"].ToString();
                    string sSql = dr["report_base_sql"].ToString();
                    string sQueryName = cmbObjects.SelectedItem.Text;
                    if (sSql.Contains("$") || sSql.Contains("#"))
                    {
                        SqlConnection sqlConn = new SqlConnection(Session["dbcon"].ToString());
                        sqlConn.Open();
                        /*string*/ sSql = getSql(); ;
                        SqlCommand sqlComm = new SqlCommand(sSql);
                        sqlComm.Connection = sqlConn;
                        SqlDataReader sqlReader = sqlComm.ExecuteReader(CommandBehavior.SchemaOnly);
                        DataTable dtSchema = sqlReader.GetSchemaTable();
                        if (dtSchema != null)
                        {
                            for (int iCount = 0; iCount <= dtSchema.Rows.Count; iCount++)
                            {
                                //foreach (DataRow dr in dtSchema.Rows)
                                //{
                                DataRow drS = dtSchema.Rows[iCount];
                                DataRow drReport = dsReport.Tables["p_sy_report_att"].NewRow();
                                if (drReport != null)
                                {
                                    string sCaption = drS["ColumnName"].ToString();
                                    //string sId = li.Value;

                                    drReport["rpt_id"] = hf_af_row_id1.Value;
                                    drReport["attrib_id"] = sCaption;
                                    drReport["object_id"] = cmbObjects.SelectedItem.Value;
                                    if (IsEdit)
                                    {
                                        string sTemp = "";
                                        //DataRow[] drr = GlobalValues.dsAudit.Tables["p_sy_report_att"].Select("object_id='" + drReport["object_id"].ToString() + "' and attrib_id='" + drReport["attrib_id"].ToString() + "'"); //Commanded by 'Imran Gani' on 23/02/2012, to avoid GlobalValues.dsAufit.
                                        DataRow[] drr = dsReport.Tables["p_sy_report_att"].Select("objec    t_id='" + drReport["object_id"].ToString() + "' and attrib_id='" + drReport["attrib_id"].ToString() + "'"); //Added by 'Imran Gani' on 23/02/2012, to avoid GlobalValues.dsAufit.
                                        if (drr.Length > 0)
                                            sTemp = drr[0]["af_row_id"].ToString();
                                        if (sTemp == "") sTemp = SR.getHashKey();
                                        drReport["af_row_id"] = sTemp;
                                    }
                                    else
                                        drReport["af_row_id"] = SR.getHashKey();
                                    drReport["caption"] = sCaption;
                                    drReport["attrib_sequence"] = iCount;

                                    fillDefaultColumns(ref drReport, DateTime.Now.ToString());

                                    dsReport.Tables["p_sy_report_att"].Rows.Add(drReport);
                                }
                            }
                        }
                        dtSchema.Dispose();
                        dtSchema = null;
                        sqlReader.Close();
                        sqlReader = null;
                        sqlComm.Dispose();
                        sqlComm = null;
                        sqlConn.Close();
                        sqlConn.Dispose();
                        sqlConn = null;
                    }
                }
            }
        }

        catch (Exception Ex)
        {
            LogWriter.WriteLog("" + Ex.Message);
        }
    }
   
    protected void rbMasterDetail_CheckedChanged(object sender, EventArgs e)
    {
     //   sReportType = rbMasterDetail.Text;
    }

    private void deleteOriginalTables(ref DataSet dsReport)
    {
        try
        {
            if (dsReport.Tables.Contains("p_sy_report"))
                dsReport.Tables.Remove("p_sy_report");
            
            if (dsReport.Tables.Contains("p_sy_report_obj"))
                dsReport.Tables.Remove("p_sy_report_obj");
            
            if (dsReport.Tables.Contains("p_sy_report_att"))
                dsReport.Tables.Remove("p_sy_report_att");
            
            if (dsReport.Tables.Contains("p_report_grouping"))
                dsReport.Tables.Remove("p_report_grouping");
            
            if (dsReport.Tables.Contains("p_report_grouping_header"))
                dsReport.Tables.Remove("p_report_grouping_header");

            if (dsReport.Tables.Contains("p_report_grouping_subtotal"))
                dsReport.Tables.Remove("p_report_grouping_subtotal");

            #region commented for phase-1
            //if (dsReport.Tables.Contains("p_report_grouping_sort_details"))
            //    dsReport.Tables.Remove("p_report_grouping_sort_details");
            #endregion

            if (dsReport.Tables.Contains("p_report_grouping_grand_total"))
                dsReport.Tables.Remove("p_report_grouping_grand_total");

            if (dsReport.Tables.Contains("p_report_header_footer"))
                dsReport.Tables.Remove("p_report_header_footer");
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("deleteOriginalTables : Error : " + ex.Message);
        }
    }

    private void deleteTempTables(ref DataSet dsReport)
    {
        try
        {
            if (dsReport.Tables.Contains("p_sy_report"))
                dsReport.Tables.Remove("p_sy_report");

            if (dsReport.Tables.Contains("step2_field_prop"))
                dsReport.Tables.Remove("step2_field_prop");

            if (dsReport.Tables.Contains("step3_report_grouping"))
                dsReport.Tables.Remove("step3_report_grouping");

            if (dsReport.Tables.Contains("step3_report_grouping_header"))
                dsReport.Tables.Remove("step3_report_grouping_header");

            if (dsReport.Tables.Contains("step3_report_grouping_subtotal"))
                dsReport.Tables.Remove("step3_report_grouping_subtotal");
            
            #region commented for phase-1
            //if (dsReport.Tables.Contains("step3_report_grouping_sort_details"))
            //    dsReport.Tables.Remove("step3_report_grouping_sort_details");
            #endregion

            if (dsReport.Tables.Contains("step3_report_grouping_grand_total"))
                dsReport.Tables.Remove("step3_report_grouping_grand_total");

            if (dsReport.Tables.Contains("step4_report_details"))
                dsReport.Tables.Remove("step4_report_details");

            if (dsReport.Tables.Contains("step5_save_report"))
                dsReport.Tables.Remove("step5_save_report");
        }
        catch (Exception ex)
        { 
            LogWriter.WriteLog("deleteTempTables : Error : " + ex.Message);
        }
    }

    private bool checkIsCopy(ref DataSet dsReport)
    {
        bool isCopy = false;
        try
        {
            if (Request.QueryString["PK"] != null)
            {
                if (Request.QueryString["CPY"] != null)
                {
                    if (Request.QueryString["CPY"] == "0")
                    {
                        IsEdit = false;
                        //deleteOriginalTables(ref dsReport);
                        hf_af_row_id1.Value = SR.getHashKey();
                        isCopy = true;
                    }
                }
                else if (hiddenTmp.Value.Trim().ToLower() == "saveas")
                {
                    IsEdit = false;
                    //deleteOriginalTables(ref dsReport);
                    hf_af_row_id1.Value = SR.getHashKey();
                    isCopy = true;
                }
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("checkIsCopy : Error : " + ex.Message);
        }
        return isCopy;
    }

    private bool SaveData()
    {
        //implemented During Report Control Change
        #region implemented During Report Control Change

        if (dsReport.Tables["p_sy_report"].Rows[0]["rpt_base_object"].ToString().ToLower() == "object")
        {
            if ((dsReport.Tables["p_sy_report_att"] != null) && (dsReport.Tables["p_sy_report_att"].Columns["temp_attrib_id"] != null))
            {
                foreach (DataRow dr in dsReport.Tables["p_sy_report_att"].Rows)
                {
                    dr["attrib_id"] = dr["temp_attrib_id"];
                }
                dsReport.Tables["p_sy_report_att"].Columns.Remove("temp_attrib_id");
            }
        }


        #endregion


        bool bReturn = true;
        Master objMaster = new Master();
        try
        {            
            if (fillInputData(ref dsReport))
            {
                if (!validateOwnerid())
                {
                    return false;
                }

                //added by Sampath on 10-Nov-2011 for Encoding
                //CommonFunctions.encodeData(dsReport);

                //deleteTempTables(ref dsReport);
                if ((!IsEdit) && (!IsExist(dsReport.Tables["p_sy_report"])))//Isexist() function added by karthik to avoide duplicates
                    bReturn = objMaster.ProcessOperation(dsPageInfo, dsReport, "INSERT");
                else
                    bReturn = updateReportData(ref dsReport);

                if (!bReturn)
                    lblMessage.Text = objMaster.ErrorMessage;
            }
            else
                bReturn = false;
        }

        catch (Exception ex)
        {
            bReturn = false;
            LogWriter.WriteLog("SaveData : Error : " + ex.Message);
        }

        return bReturn;
    }
    /// <summary>
    /// [Karthik]
    /// In some cases where in report designer user click "save&Export" Export happens, 
    /// and the page stay there, and if the user clicks finish, it will create duplicate entry 
    /// in report table, this function will chech its existence in the table
    /// </summary>
    /// <returns>If the report already exists it will return true else false</returns>
    private bool IsExist(DataTable reportTable)
    {
        try
        {
            if (reportTable.Rows.Count > 0)
                if (hdd.GetTable("sy_report", "af_row_id", "af_row_id='" + reportTable.Rows[0]["af_row_id"].ToString() + "'").Rows.Count > 0)
                    return true;
                else
                    return false;
            else
                return false;
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("SaveData : IsExist : " + ex.Message);
            return false;
        }
    }

    private bool checkRecordExists(string af_row_id, string tableName)
    {
        bool retFlag = false;
        try
        {
            DataTable dt = new DataTable();
            dt = hdd.GetDataTable("select af_row_id from " + tableName + " where af_row_id='" + af_row_id + "'");
            if (dt.Rows.Count > 0) retFlag = true;
            dt = null;
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("checkRecordExists : Error : " + ex.Message);
        }
        return retFlag;
    }

    private bool updateReportData(ref DataSet dsReport)
    {
        SqlTransaction sqlTrans = null;
        SqlConnection sqlConn = null;
        SqlCommand sqlComm = null;
        string sSql = "";
        try
        {
            sqlConn = new SqlConnection(Session["dbcon"].ToString());
            sqlConn.Open();

            //string sCreated_User = GlobalValues.dsAudit.Tables[0].Rows[0]["created_by"].ToString(); //Commanded by 'Imran Gani' on 23/02/2012, to ignore GlobalValues.dsAufit.
            //string sCreated_On = GlobalValues.dsAudit.Tables[0].Rows[0]["created_at"].ToString(); //Commanded by 'Imran Gani' on 23/02/2012, to ignore GlobalValues.dsAufit.

            string sCreated_User = dsReport.Tables[0].Rows[0]["created_by"].ToString();//Added by 'Imran Gani' on 23/02/2012, to avoid GlobalValues.dsAufit.
            string sCreated_On = dsReport.Tables[0].Rows[0]["created_at"].ToString();//Added by 'Imran Gani' on 23/02/2012, to avoid GlobalValues.dsAufit.
            
            string sOwner_id = owner_id.Value;
            sqlTrans = sqlConn.BeginTransaction();

            DataTable dt = dsReport.Tables["p_sy_report"];
            if (dt == null)
                return false;
            for (int k = 0; k < dt.Rows.Count; k++)
            {
                sSql = "update sy_report set rpt_id='" + dt.Rows[k]["rpt_id"].ToString() + "',rpt_name='" + dt.Rows[k]["rpt_name"].ToString().Replace("'", "''") + "',rpt_desc='" + dt.Rows[k]["rpt_desc"].ToString().Replace("'", "''") + "',rpt_base_object='" + dt.Rows[k]["rpt_base_object"].ToString() + "',report_category='" + dt.Rows[k]["report_category"].ToString() + "',source_filter_grouping='" + dt.Rows[k]["source_filter_grouping"].ToString() + "',owner_id = '" + sOwner_id + "', created_by='" + sCreated_User + "',modified_at='" + DateTime.UtcNow.ToString() + "' where af_row_id='" + hf_af_row_id1.Value + "'"; // modified by 'Imran Gani' on 20-Jul-2012
                sqlComm = new SqlCommand(sSql, sqlConn, sqlTrans);
                sqlComm.ExecuteNonQuery();
            }
            dt = null;

            dt = dsReport.Tables["p_sy_report_obj"];
            for (int k = 0; k < dt.Rows.Count; k++)
            {
                sSql = "update sy_report_obj set rpt_id='" + hf_af_row_id1.Value + "',object_id='" + dt.Rows[k]["object_id"].ToString() + "',owner_id = '" + sOwner_id + "', created_by='" + sCreated_User + "',modified_at='" + DateTime.UtcNow.ToString() + "' where af_row_id='" + dt.Rows[k]["af_row_id"].ToString() + "'";
                sqlComm = new SqlCommand(sSql, sqlConn, sqlTrans);
                sqlComm.ExecuteNonQuery();
            }
            dt = null;

            string sqlQry = "";
            dt = dsReport.Tables["p_sy_report_att"];
            if (dt != null)
            {
                for (int k = 0; k < dt.Rows.Count; k++)
                {
                    DataRow dr = dt.Rows[k];
                    if (checkRecordExists(dr["af_row_id"].ToString(), "sy_report_att"))
                        sSql = "update sy_report_att set rpt_id='" + hf_af_row_id1.Value + "',object_id='" + dt.Rows[k]["object_id"].ToString() + "',owner_id = '" + sOwner_id + "', created_by='" + sCreated_User + "',attrib_id='" + dr["attrib_id"].ToString() + "',caption='" + dr["caption"].ToString() + "',attrib_sequence=" + k.ToString() + ",is_bold='" + dr["is_bold"].ToString() + "',is_wrap='" + dr["is_wrap"].ToString() + "',modified_at='" + DateTime.UtcNow.ToString() + "' where af_row_id='" + dr["af_row_id"].ToString() + "'";
                    else
                        sSql = "insert into sy_report_att (af_row_id,rpt_id,attrib_id,caption,object_id,attrib_sequence,created_by,created_at,modified_at,modified_by,owner_id,is_bold,is_wrap) values ('" + dr["af_row_id"].ToString() + "','" + hf_af_row_id1.Value + "','" + dr["attrib_id"].ToString() + "','" + dr["caption"].ToString() + "','" + dr["object_id"].ToString() + "'," + k.ToString() + ",'" + sCreated_User + "','" + sCreated_On + "','" + sCreated_On + "','" + sCreated_User + "','" + sOwner_id + "','" + dr["is_bold"].ToString() + "','" + dr["is_wrap"].ToString() + "')";
                    sqlQry = sqlQry + sSql + ";";
                }
                DataTable ddT = hdd.GetDataTable("select * from sy_report_att where rpt_id='" + hf_af_row_id1.Value + "'");
                if (ddT.Rows.Count != dt.Rows.Count && ddT.Rows.Count > 0)
                {
                    foreach (DataRow drr in ddT.Rows)
                    {
                        DataRow[] drF = dt.Select("af_row_id='" + drr["af_row_id"].ToString() +"'");
                        if (drF.Length == 0)
                            sqlQry = sqlQry + "delete from sy_report_att where af_row_id='" + drr["af_row_id"].ToString() + "';";
                        drF = null;
                    }
                }
                else if (ddT.Rows.Count == dt.Rows.Count && ddT.Rows.Count > 0)
                {
                    string obj_id = dt.Rows[0]["object_id"].ToString();
                    DataTable ddT1 = hdd.GetDataTable("select * from sy_report_att where rpt_id='" + hf_af_row_id1.Value + "' and object_id='" + obj_id + "'");
                    if (ddT1.Rows.Count > 0)
                    {
                        foreach (DataRow drr in ddT1.Rows)
                        {
                            DataRow[] drF = dt.Select("af_row_id='" + drr["af_row_id"].ToString() + "'");
                            if (drF.Length == 0)
                                sqlQry = sqlQry + "delete from sy_report_att where af_row_id='" + drr["af_row_id"].ToString() + "';";
                            drF = null;
                        }
                        ddT1 = null;
                    }
                    else
                        sqlQry = "delete from sy_report_att where rpt_id='" + hf_af_row_id1.Value + "';" + sqlQry;
                }
                ddT = null;
                if (sqlQry.Trim() != "")
                {
                    sqlComm = new SqlCommand(sqlQry, sqlConn, sqlTrans);
                    sqlComm.ExecuteNonQuery();
                }
            }
            dt = null;
            sqlQry = "";

            // Added by Imran Gani on 20-Jul-2012, for Source Filter.
            dt = dsReport.Tables["p_report_source_filter"];
            if (dt != null)
            {
                for (int k = 0; k < dt.Rows.Count; k++)
                {
                    DataRow dr = dt.Rows[k];
                    if (checkRecordExists(dr["af_row_id"].ToString(), "sy_report_source_filter"))
                        sSql = "update sy_report_source_filter set rpt_id='" + hf_af_row_id1.Value + "',sequence='" + dt.Rows[k]["sequence"].ToString() + "',source_object='" + dt.Rows[k]["source_object"].ToString() + "',owner_id = '" + sOwner_id + "', created_by='" + sCreated_User + "',field='" + dr["field"].ToString().Replace("'", "''") + "',condition='" + dr["condition"].ToString() + "',field_value='" + dr["field_value"].ToString().Replace("'", "''") + "',modified_at='" + DateTime.UtcNow.ToString() + "' where af_row_id='" + dr["af_row_id"].ToString() + "'";
                    else
                        sSql = "insert into sy_report_source_filter (af_row_id,rpt_id,sequence,field,condition,field_value,source_object,created_by,created_at,modified_at,modified_by,owner_id) values ('" + dr["af_row_id"].ToString() + "','" + hf_af_row_id1.Value + "','" + dr["sequence"].ToString() + "','" + dr["field"].ToString().Replace("'", "''") + "','" + dr["condition"].ToString() + "','" + dr["field_value"].ToString().Replace("'", "''") + "','" + dr["source_object"].ToString() + "','" + sCreated_User + "','" + sCreated_On + "','" + sCreated_On + "','" + sCreated_User + "','" + sOwner_id + "')";
                    sqlQry = sqlQry + sSql + ";";
                }
                DataTable ddT = hdd.GetDataTable("select * from sy_report_source_filter where rpt_id='" + hf_af_row_id1.Value + "'");
                if ((ddT.Rows.Count != dt.Rows.Count || ddT.Rows.Count == dt.Rows.Count) && ddT.Rows.Count > 0)
                {
                    foreach (DataRow drr in ddT.Rows)
                    {
                        DataRow[] drF = dt.Select("af_row_id='" + drr["af_row_id"].ToString() + "'");
                        if (drF.Length == 0)
                            sqlQry = sqlQry + "delete from sy_report_source_filter where af_row_id='" + drr["af_row_id"].ToString() + "';";
                        drF = null;
                    }
                }
                ddT = null;
                if (sqlQry.Trim() != "")
                {
                    sqlComm = new SqlCommand(sqlQry, sqlConn, sqlTrans);
                    sqlComm.ExecuteNonQuery();
                }
            }
            dt = null;
            sqlQry = "";

            ArrayList alRptKeys = new ArrayList();

            dt = dsReport.Tables["p_report_grouping"];
            if (dt != null)
            {
                for (int k = 0; k < dt.Rows.Count; k++)
                {
                    DataRow dr = dt.Rows[k];
                    if (checkRecordExists(dr["af_row_id"].ToString(), "sy_report_grouping"))
                        sSql = "update sy_report_grouping set rpt_id='" + hf_af_row_id1.Value + "',grouping_field='" + dr["grouping_field"].ToString() + "',attribute_sequence=" + (k + 1).ToString() + ",grouping_order='" + dr["grouping_order"].ToString() + "',show_header='" + dr["show_header"].ToString() + "',show_subtotal='" + dr["show_subtotal"].ToString() + "',modified_by='" + sCreated_User + "',owner_id='" + sOwner_id + "',modified_at='" + DateTime.UtcNow.ToString() + "' where af_row_id='" + dr["af_row_id"].ToString() + "'";
                    else
                        sSql = "insert into sy_report_grouping (af_row_id,rpt_id,grouping_field,attribute_sequence,grouping_order,show_header,show_subtotal,created_by,created_at,modified_at,modified_by,owner_id) values ('" + dr["af_row_id"].ToString() + "','" + hf_af_row_id1.Value + "','" + dr["grouping_field"].ToString() + "'," + (k+1).ToString() + ",'" + dr["grouping_order"].ToString() + "','" + dr["show_header"].ToString() + "','" + dr["show_subtotal"] + "','" + sCreated_User + "','" + sCreated_On + "','" + sCreated_On + "','" + sCreated_User + "','" + sOwner_id + "')";
                    sqlQry = sqlQry + sSql + ";";
                }
                DataTable ddT = hdd.GetDataTable("select * from sy_report_grouping where rpt_id='" + hf_af_row_id1.Value + "'");
                if (ddT.Rows.Count != dt.Rows.Count && ddT.Rows.Count > 0)
                {
                    foreach (DataRow drr in ddT.Rows)
                    {
                        alRptKeys.Add(drr["af_row_id"]);
                        DataRow[] drF = dt.Select("af_row_id='" + drr["af_row_id"].ToString() + "'");
                        if (drF.Length == 0)
                            sqlQry = sqlQry + "delete from sy_report_grouping where af_row_id='" + drr["af_row_id"].ToString() + "';";
                        drF = null;
                    }
                }
                ddT = null;
                if (sqlQry.Trim() != "")
                {
                    sqlComm = new SqlCommand(sqlQry, sqlConn, sqlTrans);
                    sqlComm.ExecuteNonQuery();
                }
            }
            dt = null;
            sqlQry = "";

            dt = dsReport.Tables["p_report_grouping_header"];
            if (dt != null)
            {
                for (int k = 0; k < dt.Rows.Count; k++)
                {
                    DataRow dr = dt.Rows[k];
                    if (checkRecordExists(dr["af_row_id"].ToString(), "sy_report_grouping_header"))
                        sSql = "update sy_report_grouping_header set rpt_group_id='" + dr["rpt_group_id"].ToString() + "',header_field='" + dr["header_field"].ToString() + "',group_sequence=" + dr["group_sequence"].ToString() + ",field_sequence=" + dr["field_sequence"].ToString() + ",owner_id='" + sOwner_id + "',modified_at='" + DateTime.UtcNow.ToString() + "' where af_row_id='" + dr["af_row_id"].ToString() + "'";
                    else
                        sSql = "insert into sy_report_grouping_header (af_row_id,rpt_group_id,header_field,group_sequence,field_sequence,created_by,created_at,modified_at,modified_by,owner_id) values ('" + dr["af_row_id"].ToString() + "','" + dr["rpt_group_id"].ToString() + "','" + dr["header_field"].ToString() + "'," + dr["group_sequence"].ToString() + "," + dr["field_sequence"].ToString() + ",'" + sCreated_User + "','" + sCreated_On + "','" + sCreated_On + "','" + sCreated_User + "','" + sOwner_id + "')";
                    sqlQry = sqlQry + sSql + ";";
                }

                foreach (string key in alRptKeys)
                {
                    DataTable ddT = hdd.GetDataTable("select * from sy_report_grouping_header where rpt_group_id='" + key + "'");
                    foreach (DataRow drr in ddT.Rows)
                    {
                        DataRow[] drF = dt.Select("af_row_id='" + drr["af_row_id"].ToString() + "'");
                        if (drF.Length == 0)
                            sqlQry = sqlQry + "delete from sy_report_grouping_header where af_row_id='" + drr["af_row_id"].ToString() + "';";
                        drF = null;
                    }
                    ddT = null;
                }

                if (sqlQry.Trim() != "")
                {
                    sqlComm = new SqlCommand(sqlQry, sqlConn, sqlTrans);
                    sqlComm.ExecuteNonQuery();
                }
            }
            dt = null;
            sqlQry = "";

            dt = dsReport.Tables["p_report_grouping_subtotal"];
            if (dt != null)
            {
                for (int k = 0; k < dt.Rows.Count; k++)
                {
                    DataRow dr = dt.Rows[k];
                    if (checkRecordExists(dr["af_row_id"].ToString(), "sy_report_grouping_subtotal"))
                        sSql = "update sy_report_grouping_subtotal set rpt_group_id='" + dr["rpt_group_id"].ToString() + "',subtotal_field='" + dr["subtotal_field"].ToString() + "',group_sequence=" + dr["group_sequence"].ToString() + ",field_sequence=" + dr["field_sequence"].ToString() + ",owner_id='" + sOwner_id + "',modified_at='" + DateTime.UtcNow.ToString() + "' where af_row_id='" + dr["af_row_id"].ToString() + "'";
                    else
                        sSql = "insert into sy_report_grouping_subtotal (af_row_id,rpt_group_id,subtotal_field,group_sequence,field_sequence,created_by,created_at,modified_at,modified_by,owner_id) values ('" + dr["af_row_id"].ToString() + "','" + dr["rpt_group_id"].ToString() + "','" + dr["subtotal_field"].ToString() + "'," + dr["group_sequence"].ToString() + "," + dr["field_sequence"].ToString() + ",'" + sCreated_User + "','" + sCreated_On + "','" + sCreated_On + "','" + sCreated_User + "','" + sOwner_id + "')";
                    sqlQry = sqlQry + sSql + ";";
                }
                foreach (string key in alRptKeys)
                {
                    DataTable ddT = hdd.GetDataTable("select * from sy_report_grouping_subtotal where rpt_group_id='" + key + "'");
                    foreach (DataRow drr in ddT.Rows)
                    {
                        DataRow[] drF = dt.Select("af_row_id='" + drr["af_row_id"].ToString() + "'");
                        if (drF.Length == 0)
                            sqlQry = sqlQry + "delete from sy_report_grouping_subtotal where af_row_id='" + drr["af_row_id"].ToString() + "';";
                        drF = null;
                    }
                    ddT = null;
                }
                if (sqlQry.Trim() != "")
                {
                    sqlComm = new SqlCommand(sqlQry, sqlConn, sqlTrans);
                    sqlComm.ExecuteNonQuery();
                }
            }
            dt = null;
            alRptKeys.Clear();
            alRptKeys = null;
            sqlQry = "";

            #region commented for phase-1
            //dt = dsReport.Tables["p_report_grouping_sort_details"];
            //if (dt != null)
            //{
            //    for (int k = 0; k < dt.Rows.Count; k++)
            //    {
            //        DataRow dr = dt.Rows[k];
            //        if (dr.RowState == DataRowState.Added)
            //            sSql = "insert into sy_report_grouping_sort_details (af_row_id,rpt_id,sort_detail_field,sort_detail_order,attribute_sequence,created_by,created_at,modified_at,modified_by,owner_id) values ('" + dr["af_row_id"].ToString() + "','" + hf_af_row_id1.Value + "','" + dr["sort_detail_field"].ToString() + "'," + dr["sort_detail_order"].ToString() + "," + dr["attribute_sequence"].ToString() + ",'" + sCreated_User + "','" + sCreated_On + "','" + sCreated_On + "','" + sCreated_User + "','" + sOwner_id + "')";
            //        else if (dr.RowState == DataRowState.Modified)
            //            sSql = "update sy_report_grouping_sort_details set rpt_id='" + hf_af_row_id1.Value + "',sort_detail_field='" + dr["sort_detail_field"].ToString() + "',sort_detail_order=" + dr["sort_detail_order"].ToString() + ",attribute_sequence=" + dr["attribute_sequence"].ToString() + ",owner_id='" + sOwner_id + "' where af_row_id='" + dr["af_row_id"].ToString() + "'";
            //        else
            //            continue;
            //        sqlQry = sqlQry + sSql + ";";
            //    }
            //    if (sqlQry.Trim() != "")
            //    {
            //        sqlComm = new SqlCommand(sqlQry, sqlConn, sqlTrans);
            //        sqlComm.ExecuteNonQuery();
            //    }
            //}
            //dt = null;
            //sqlQry = "";
            #endregion

            dt = dsReport.Tables["p_report_grouping_grand_total"];
            if (dt != null)
            {
                for (int k = 0; k < dt.Rows.Count; k++)
                {
                    DataRow dr = dt.Rows[k];
                    if (checkRecordExists(dr["af_row_id"].ToString(), "sy_report_grouping_grand_total"))
                        sSql = "update sy_report_grouping_grand_total set rpt_id='" + hf_af_row_id1.Value + "',grand_total_field='" + dr["grand_total_field"].ToString() + "',attribute_sequence=" + dr["attribute_sequence"].ToString() + ",owner_id='" + sOwner_id + "',modified_at='" + DateTime.UtcNow.ToString() + "' where af_row_id='" + dr["af_row_id"].ToString() + "'";
                    else
                        sSql = "insert into sy_report_grouping_grand_total (af_row_id,rpt_id,grand_total_field,attribute_sequence,created_by,created_at,modified_at,modified_by,owner_id) values ('" + dr["af_row_id"].ToString() + "','" + hf_af_row_id1.Value + "','" + dr["grand_total_field"].ToString() + "'," + dr["attribute_sequence"].ToString() + ",'" + sCreated_User + "','" + sCreated_On + "','" + sCreated_On + "','" + sCreated_User + "','" + sOwner_id + "')";
                    sqlQry = sqlQry + sSql + ";";
                }
                DataTable ddT = hdd.GetDataTable("select * from sy_report_grouping_grand_total where rpt_id='" + hf_af_row_id1.Value + "'");
                if (ddT.Rows.Count != dt.Rows.Count && ddT.Rows.Count > 0)
                {
                    foreach (DataRow drr in ddT.Rows)
                    {
                        DataRow[] drF = dt.Select("af_row_id='" + drr["af_row_id"].ToString() + "'");
                        if (drF.Length == 0)
                            sqlQry = sqlQry + "delete from sy_report_grouping_grand_total where af_row_id='" + drr["af_row_id"].ToString() + "';";
                        drF = null;
                    }
                }
                ddT = null;
                if (sqlQry.Trim() != "")
                {
                    sqlComm = new SqlCommand(sqlQry, sqlConn, sqlTrans);
                    sqlComm.ExecuteNonQuery();
                }
            }
            dt = null;
            sqlQry = "";

            dt = dsReport.Tables["p_report_header_footer"];
            if (dt != null)
            {
                for (int k = 0; k < dt.Rows.Count; k++)
                {
                    DataRow dr = dt.Rows[k];
                    if (checkRecordExists(dr["af_row_id"].ToString(), "sy_report_header_footer"))
                        sSql = "update sy_report_header_footer set rpt_id='" + hf_af_row_id1.Value + "',rpt_title='" + dr["rpt_title"].ToString().Replace("'", "''") + "',rpt_head_text='" + dr["rpt_head_text"].ToString().Replace("'", "''") + "',rpt_foot_text='" + dr["rpt_foot_text"].ToString().Replace("'", "''") + "',rpt_logo='" + dr["rpt_logo"].ToString() + "',rpt_page_no='" + dr["rpt_page_no"].ToString() + "',rpt_date='" + dr["rpt_date"].ToString() + "',owner_id='" + sOwner_id + "',modified_at='" + DateTime.UtcNow.ToString() + "' where af_row_id='" + dr["af_row_id"].ToString() + "'";
                    else
                        sSql = "insert into sy_report_header_footer (af_row_id,rpt_id,rpt_title,rpt_head_text,rpt_foot_text,rpt_logo,rpt_page_no,rpt_date,created_by,created_at,modified_at,modified_by,owner_id) values ('" + dr["af_row_id"].ToString() + "','" + hf_af_row_id1.Value + "','" + dr["rpt_title"].ToString().Replace("'", "''") + "','" + dr["rpt_head_text"].ToString().Replace("'", "''") + "','" + dr["rpt_foot_text"].ToString().Replace("'", "''") + "','" + dr["rpt_logo"].ToString() + "','" + dr["rpt_page_no"].ToString() + "','" + dr["rpt_date"].ToString() + "','" + sCreated_User + "','" + sCreated_On + "','" + sCreated_On + "','" + sCreated_User + "','" + sOwner_id + "')";
                    sqlQry = sqlQry + sSql + ";";
                }
                if (sqlQry.Trim() != "")
                {
                    sqlComm = new SqlCommand(sqlQry, sqlConn, sqlTrans);
                    sqlComm.ExecuteNonQuery();
                }
            }
            dt = null;
            sqlQry = "";
            sqlTrans.Commit();

            sqlConn.Close();
        }
        catch (Exception ex)
        {
            sqlTrans.Rollback();
            LogWriter.WriteLog("updateReportData : Error : " + ex.Message);
        }
        finally
        {            
            sqlConn = null;
            sqlTrans = null;
            sqlComm = null;
        }
        return true;
    }

    //protected void btnUpdate_Click(object sender, EventArgs e)
    //{
    //    bool bReturn = true;
    //    Master objMaster = new Master();
    //    try
    //    {
    //        if (fillInputData(ref dsReport))
    //        {
    //            bReturn = objMaster.ProcessOperation(dsPageInfo, dsReport, "UPDATE");

    //            if (!bReturn)
    //                lblMessage.Text = objMaster.ErrorMessage;
    //        }
    //    }
    //    catch (Exception ex)
    //    {
    //        bReturn = false;
    //        LogWriter.WriteLog(this.Title + " : Error : " + ex.Message);
    //    }
    //}

    protected void Page_PreRenderComplete(object sender, EventArgs e)
    {
        //Session.Add("ReportInput", dsInputInfo);
    }

    private string getAttributeName(string AttributeId)
    {
        string sAttributeName = "";
        string sSql = "Select attrib_name from sy_obj_att where attrib_id = '" + AttributeId + "'";
        sAttributeName = hdd.GetColumnValue(sSql);
        return sAttributeName;
    }

    protected void imgUp_Click(object sender, ImageClickEventArgs e)
    {
        int iSelectedIndex = lstSelectedFields1.SelectedIndex;
        if (iSelectedIndex != -1)
        {
            if (iSelectedIndex != 0)
            {
                ListItem li = lstSelectedFields1.SelectedItem;
                lstSelectedFields1.Items.RemoveAt(iSelectedIndex);
                lstSelectedFields1.Items.Insert(iSelectedIndex - 1, li);
            }
        }
    }
    
    protected void imgDown_Click(object sender, ImageClickEventArgs e)
    {
        int iSelectedIndex = lstSelectedFields1.SelectedIndex;
        if (iSelectedIndex != -1)
        {
            if (iSelectedIndex != lstSelectedFields1.Items.Count - 1)
            {
                ListItem li = lstSelectedFields1.SelectedItem;
                lstSelectedFields1.Items.RemoveAt(iSelectedIndex);
                lstSelectedFields1.Items.Insert(iSelectedIndex + 1, li);
            }
        }
    }

    private void disableControls(string Object_Name)
    {
        switch (Object_Name.ToLower())
        {
            case "sy_report":
                txtHeaderText.Enabled = false;
                txtReportDesc.Enabled = false;
                //rbTabular.Enabled = false;
                //rbMatrix.Enabled = false;
                //rbMasterDetail.Enabled = false;
                //rbAllObjects.Enabled = false;
                //rbPredefinedObjects.Enabled = false;
                break;
            case "sy_report_obj":
            case "sy_report_att":
                cmbObjects.Enabled = false;
                lstFields1.Enabled = false;
                lstSelectedFields1.Enabled = false;
                imgSelect1.Enabled = false;
                imgUnselect1.Enabled = false;
                imgUp1.Enabled = false;
                imgDown1.Enabled = false;
                lblFieldsMsg1.Text = "You do not have sufficient access permission.";
                lblFieldsMsg1.ForeColor = System.Drawing.Color.Red;
                break;
            //case "sy_report_att":
            //    tblProperties.Disabled = true;
            //    lblMsgStep3.Text = "You do not have sufficient access permission.";
            //    lblMsgStep2.ForeColor = System.Drawing.Color.Red;
            //    break;
        }
    }

    private void getInputDataSet(ref DataSet dsReport)
    {
        try
        {
            string sObject_id = "sy_report";
            if (hdds.getObjectRightsForUser(sObject_id, "read"))
            {
                string sSql = "select * from sy_report where af_row_id = '" + m_PageKey + "'";
                DataTable dt = hdd.GetDataTable(sSql);
                dt.TableName = "p_sy_report";
                dsReport.Tables.Add(dt.Copy());

                sObject_id = "sy_report_obj";
                if (hdds.getObjectRightsForUser("sy_report_obj", "read"))
                {
                    sSql = "select * from sy_report_obj where rpt_id = '" + m_PageKey + "'";
                    dt = hdd.GetDataTable(sSql, "p_sy_report_obj");
                    dsReport.Tables.Add(dt.Copy());
                }
                else
                    disableControls(sObject_id);

                sObject_id = "sy_report_att";
                if (hdds.getObjectRightsForUser("sy_report_att", "read"))
                {
                    sSql = "select * from sy_report_att where rpt_id = '" + m_PageKey + "'";
                    dt = hdd.GetDataTable(sSql, "p_sy_report_att");
                    dsReport.Tables.Add(dt.Copy());
                }
                else
                    disableControls(sObject_id);

                sObject_id = "ob_report_source_filter"; // Added by Imran Gani on 20-Jul-2012, for Source Filter.
                if (hdds.getObjectRightsForUser("ob_report_source_filter", "read"))
                {
                    sSql = "select * from sy_report_source_filter where rpt_id = '" + m_PageKey + "'";
                    dt = hdd.GetDataTable(sSql, "p_report_source_filter");
                    dsReport.Tables.Add(dt.Copy());
                }

                sObject_id = "ob_report_grouping";
                ArrayList alKeys = new ArrayList();
                if (hdds.getObjectRightsForUser("ob_report_grouping", "read"))
                {
                    sSql = "select * from sy_report_grouping where rpt_id = '" + m_PageKey + "'";
                    dt = hdd.GetDataTable(sSql, "p_report_grouping");

                    if (dt.Rows.Count == 0)
                    {
                        string tSql = "select * from sy_report_grouping_header where rpt_group_id='" + m_PageKey + "'";
                        DataTable dtTmp = hdd.GetDataTable(tSql, "p_report_grouping_header");
                        if (!dsReport.Tables.Contains(dtTmp.TableName))
                            dsReport.Tables.Add(dtTmp.Copy());
                        else
                            dsReport.Tables[dtTmp.TableName].Merge(dtTmp);

                        tSql = "select * from sy_report_grouping_subtotal where rpt_group_id='" + m_PageKey + "'";
                        dtTmp = hdd.GetDataTable(tSql, "p_report_grouping_subtotal");
                        if (!dsReport.Tables.Contains(dtTmp.TableName))
                            dsReport.Tables.Add(dtTmp.Copy());
                        else
                            dsReport.Tables[dtTmp.TableName].Merge(dtTmp);
                    }

                    foreach (DataRow dr in dt.Rows)
                    {
                        string tSql = "select * from sy_report_grouping_header where rpt_group_id='" + dr["af_row_id"].ToString() + "'";
                        if (hdds.getObjectRightsForUser("ob_report_grouping_header", "read"))
                        {
                            DataTable dtTmp = hdd.GetDataTable(tSql, "p_report_grouping_header");
                            if (!dsReport.Tables.Contains(dtTmp.TableName))
                                dsReport.Tables.Add(dtTmp.Copy());
                            else
                                dsReport.Tables[dtTmp.TableName].Merge(dtTmp);
                        }
                        else
                            disableControls("ob_report_grouping_header");
                    }

                    foreach (DataRow dr in dt.Rows)
                    {
                        string tSql = "select * from sy_report_grouping_subtotal where rpt_group_id='" + dr["af_row_id"].ToString() + "'";
                        if (hdds.getObjectRightsForUser("ob_report_grouping_subtotal", "read"))
                        {
                            DataTable dtTmp = hdd.GetDataTable(tSql, "p_report_grouping_subtotal");
                            if (!dsReport.Tables.Contains(dtTmp.TableName))
                                dsReport.Tables.Add(dtTmp.Copy());
                            else
                                dsReport.Tables[dtTmp.TableName].Merge(dtTmp);
                        }
                        else
                            disableControls("ob_report_grouping_subtotal");
                    }
                    dsReport.Tables.Add(dt.Copy());
                }
                else
                    disableControls(sObject_id);

                #region commented for phase-1
                //sObject_id = "ob_report_grouping_sort_details";
                //if (hdds.getObjectRightsForUser("ob_report_grouping_sort_details", "read"))
                //{
                //    sSql = "select * from sy_report_grouping_sort_details where rpt_id = '" + m_PageKey + "'";
                //    dt = hdd.GetDataTable(sSql, "p_report_grouping_sort_details");
                //    dsReport.Tables.Add(dt.Copy());
                //}
                //else
                //    disableControls(sObject_id);
                #endregion

                sObject_id = "ob_report_grouping_grand_total";
                if (hdds.getObjectRightsForUser("ob_report_grouping_grand_total", "read"))
                {
                    sSql = "select * from sy_report_grouping_grand_total where rpt_id = '" + m_PageKey + "'";
                    dt = hdd.GetDataTable(sSql, "p_report_grouping_grand_total");
                    dsReport.Tables.Add(dt.Copy());
                }
                else
                    disableControls(sObject_id);

                sObject_id = "ob_report_header_footer";
                if (hdds.getObjectRightsForUser("ob_report_header_footer", "read"))
                {
                    sSql = "select * from sy_report_header_footer where rpt_id = '" + m_PageKey + "'";
                    dt = hdd.GetDataTable(sSql, "p_report_header_footer");
                    dsReport.Tables.Add(dt.Copy());
                }
                else
                    disableControls(sObject_id);
            }
            else
                disableControls(sObject_id);
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("getInputDataSet" + " : Error : " + ex.Message);
        }
    }

    private bool getData()
    {
        try
        {
            dsReport = new DataSet();

            getInputDataSet(ref dsReport);

            if (IsEdit)
            {
                if (Session["report_ds"] == null)
                    Session.Add("report_ds", dsReport);
                else
                    Session["report_ds"] = dsReport;
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("getData" + " : Error : " + ex.Message);
        }
        return true;
    }

    private string getAttribAfRowID(string attribId, string objectId)
    {
        string attribAfRowId = "";
        try
        {
            DataTable dt = hdd.GetDataTable("select af_row_id from sy_obj_att where attrib_id='" + attribId + "' and [object_id]=(select af_row_id from sy_obj where [object_id]='" + objectId + "')");
            if (dt != null)
            {
                if (dt.Rows.Count > 0)
                    attribAfRowId = dt.Rows[0]["af_row_id"].ToString();
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("getAttribAfRowID" + " : Error : " + ex.Message);
        }
        return attribAfRowId;
    }

    private bool setData(bool IsEdit)
    {
        bool isOldReport = false;
        try
        {
            if (dsReport.Tables["p_sy_report"].Rows.Count == 0) return false;

            //added by Sampath on 10-Nov-2011 for Encoding
            //CommonFunctions.decodeData(dsReport);

            //Substituting Step 1 values
            if (IsEdit)
                lblReportId.Text = dsReport.Tables["p_sy_report"].Rows[0]["rpt_id"].ToString();
            else
                lblReportId.Text = getReportId();

            string baseobj = dsReport.Tables["p_sy_report"].Rows[0]["rpt_base_object"].ToString();

            if (baseobj.ToLower() == "true")
            {
                baseobj = "SQL";
                isOldReport = true;
            }
            else if (baseobj.ToLower() == "false")
            {
                baseobj = "OBJECT";
                isOldReport = true;
            }            

            lblReportSrc.Text = baseobj;

            if (cmbObjects.Items.Count == 0)
            {
                string sSql = "Select * from sy_obj order by object_name asc";
                loadObjectsinCombo(sSql);
            }

            //Backward compatibility
            if (dsReport.Tables.Contains("p_sy_report_obj"))
            {
                if (dsReport.Tables["p_sy_report_obj"].Rows.Count > 0)
                    cmbObjects.Text = baseobj.ToUpper() + "@" + dsReport.Tables["p_sy_report_obj"].Rows[0]["object_id"].ToString();
            }

            foreach (DataRow dr in dsReport.Tables["p_sy_report"].Rows)
            {
                txtRepName.Text = dr["rpt_name"].ToString();
                txtReportDesc.Text = dr["rpt_desc"].ToString();
                owner_id.Value = dr["owner_id"].ToString();
                hf_af_row_id1.Value = dr["af_row_id"].ToString();
                txtReportCategory.Text = dr["report_category"].ToString(); // Added by 'Imran Gani' on 28-May-2012, for report category.
            }

            string objectId = "[" + cmbObjects.SelectedValue.Substring(cmbObjects.SelectedValue.IndexOf("@") + 1) + "].[";

            if (isOldReport)
            {
                DataTable dt = dsReport.Tables["p_sy_report_att"];
                if (baseobj == "OBJECT")
                {
                    for (int k = 0; k < dt.Rows.Count; k++)
                    {
                        DataRow dr = dt.Rows[k];
                        dr["attrib_id"] = getAttribAfRowID(dr["attrib_id"].ToString(), cmbObjects.SelectedValue.Substring(cmbObjects.SelectedValue.IndexOf("@") + 1));
                        dr["is_wrap"] = true;
                        dr["is_bold"] = false;
                    }
                }
                else if (baseobj == "SQL")
                {
                    for (int k = 0; k < dt.Rows.Count; k++)
                    {
                        DataRow dr = dt.Rows[k];
                        dr["is_wrap"] = true;
                        dr["is_bold"] = false;
                    }
                }
            }

            if (dsReport.Tables.Contains("p_sy_report_att"))
            {
                if (dsReport.Tables["p_sy_report_att"].Rows.Count > 0)
                {
                    createDataTable(1, ref dsReport);
                    populateListBox(lstFields1, null);
                    foreach (DataRow dr in dsReport.Tables["p_sy_report_att"].Rows)
                    {
                        ListItem li = null;
                        //if (isOldReport)
                        //{
                        //    if (baseobj.ToUpper() == "SQL")
                        //        li = lstFields1.Items.FindByValue("[" + dr["object_id"].ToString() + "].[" + dr["attrib_id"].ToString() + "]");
                        //    else if (baseobj.ToUpper() == "OBJECT")
                        //        li = lstFields1.Items.FindByValue("[" + dr["object_id"].ToString() + "].[" + getAttribAfRowID(dr["attrib_id"].ToString(), cmbObjects.SelectedValue.Substring(cmbObjects.SelectedValue.IndexOf("@") + 1)) + "]");
                        //}
                        //else
                        li = lstFields1.Items.FindByValue("[" + dr["object_id"].ToString() + "].[" + dr["attrib_id"].ToString() + "]");
                        if (li != null)
                        {
                            lstFields1.Items.Remove(li);
                            lstSelectedFields1.Items.Add(li);
                        }
                    }

                    showFieldProperties();

                    for (int k = 0; k < dsReport.Tables["p_sy_report_att"].Rows.Count; k++ )
                    {
                        DataRow dr = dsReport.Tables["p_sy_report_att"].Rows[k];
                        Label lbl = (Label)this.Master.FindControl("ContentPlaceHolder3").FindControl("wz_report").FindControl("lbl_caption_" + "[" + dr["object_id"].ToString() + "].[" + dr["attrib_id"].ToString() + "]");
                        lbl.Text = dr["attrib_id"].ToString();

                        TextBox txtBox = (TextBox)this.Master.FindControl("ContentPlaceHolder3").FindControl("wz_report").FindControl("txt_" + "[" + dr["object_id"].ToString() + "].[" + dr["attrib_id"].ToString() + "]");
                        txtBox.Text = setCaption(lblReportSrc.Text, dr["attrib_id"].ToString(), dr["caption"].ToString());

                        DropDownList dd1 = (DropDownList)this.Master.FindControl("ContentPlaceHolder3").FindControl("wz_report").FindControl("dd_" + "[" + dr["object_id"].ToString() + "].[" + dr["attrib_id"].ToString() + "]" + "_bold");
                        dd1.Text = dr["is_bold"].ToString().ToLower() == "true" ? "Yes" : "No";

                        dd1 = (DropDownList)this.Master.FindControl("ContentPlaceHolder3").FindControl("wz_report").FindControl("dd_" + "[" + dr["object_id"].ToString() + "].[" + dr["attrib_id"].ToString() + "]" + "_wwrap");
                        dd1.Text = dr["is_wrap"].ToString().ToLower() == "true" ? "Yes" : "No";
                        
                        string tmpObjectId = "[" + dr["object_id"].ToString() + "].[";

                        dr["attrib_id"] = tmpObjectId + dr["attrib_id"].ToString() + "]";
                        dr["caption"] = setCaption(lblReportSrc.Text, dr["attrib_id"].ToString(), dr["caption"].ToString());
                        dr["is_bold"] = dr["is_bold"].ToString();
                        dr["is_wrap"] = dr["is_wrap"].ToString();
                    }
                }
            }

            //Grouping 
            hiddenGroupCnt.Value = dsReport.Tables["p_report_grouping"].Rows.Count.ToString();
            if (dsReport.Tables["p_report_grouping"].Rows.Count == 0)
                hiddenGroupCnt.Value = "1";

            for (int k = 2; k <= dsReport.Tables["p_report_grouping"].Rows.Count; k++)
                createGroupingForm(k);
            //Assigning values

            lblMsgStep2.Text = cmbObjects.SelectedItem.Text + "$" + cmbObjects.SelectedValue.Substring(cmbObjects.SelectedValue.IndexOf("@") + 1);

            int groupCnt = dsReport.Tables["p_report_grouping"].Rows.Count;

            for (int k = 1; k <= dsReport.Tables["p_report_grouping"].Rows.Count; k++)
            {
                DataRow dr = dsReport.Tables["p_report_grouping"].Rows[k-1];
                
                DropDownList ddList = (DropDownList)this.Master.FindControl("ContentPlaceHolder3").FindControl("wz_report").FindControl("PlaceHolder_group").FindControl("ddl_group_field_" + k.ToString());
                if (ddList != null)
                {
                    if (ddList.Items.Count == 1)
                        populateFieldsFromSelectedList(ref ddList);
                    ddList.Text = objectId + dr["grouping_field"].ToString() + "]";
                }
                
                ddList = (DropDownList)this.Master.FindControl("ContentPlaceHolder3").FindControl("wz_report").FindControl("PlaceHolder_group").FindControl("ddl_group_order_" + k.ToString());
                if (ddList != null)
                    ddList.Text = dr["grouping_order"].ToString();
                //dr["grouping_order"] = dr["grouping_order"].ToString();

                CheckBox cb = (CheckBox)this.Master.FindControl("ContentPlaceHolder3").FindControl("wz_report").FindControl("PlaceHolder_group").FindControl("cb_showhdr_" + k.ToString());
                if (cb != null)
                    cb.Checked = Convert.ToBoolean(dr["show_header"].ToString());
                //dr1["show_header"] = dr["show_header"].ToString();

                cb = (CheckBox)this.Master.FindControl("ContentPlaceHolder3").FindControl("wz_report").FindControl("PlaceHolder_group").FindControl("cb_showsub_" + k.ToString());
                if (cb != null)
                    cb.Checked = Convert.ToBoolean(dr["show_subtotal"].ToString());
                //dr1["show_subtotal"] = dr["show_subtotal"].ToString();

                dr["grouping_field"] = objectId + dr["grouping_field"].ToString() + "]";
                //dt1.Rows.Add(dr1);
            }
            //dt1 = null;
            //Header
            //dt1 = dsReport.Tables["step3_report_grouping_header"];
            for (int k = 1; k <= groupCnt; k++)
            {                
                int idx = 0;
                foreach(DataRow dr in dsReport.Tables["p_report_grouping_header"].Select("group_sequence=" + k.ToString()))
                {
                    DropDownList ddList = (DropDownList)this.Master.FindControl("ContentPlaceHolder3").FindControl("wz_report").FindControl("PlaceHolder_group").FindControl("ddl_hdr_field" + dr["field_sequence"].ToString() + "_" + dr["group_sequence"].ToString());
                    if (ddList != null)
                    {
                        if (ddList.Items.Count == 1)
                            populateFieldsFromSelectedList(ref ddList);
                        ddList.Text = objectId + dr["header_field"].ToString() + "]";
                        
                        //DataRow dr1 = dt1.NewRow();
                        //dr1["af_row_id"] = dr["af_row_id"];
                        //dr1["rpt_group_id"] = dr["group_sequence"].ToString();
                        //dr1["group_sequence"] = dr["group_sequence"].ToString();
                        dr["header_field"] = objectId + dr["header_field"].ToString() + "]";
                        //dr1["field_sequence"] = dr["field_sequence"];
                        //dt1.Rows.Add(dr1);
                    }
                    
                    idx++;
                }
            }
            //dt1 = null;

            //Subtotal
            //dt1 = dsReport.Tables["step3_report_grouping_subtotal"];
            for (int k = 1; k <= groupCnt; k++)
            {
                int idx = 0;
                foreach (DataRow dr in dsReport.Tables["p_report_grouping_subtotal"].Select("group_sequence=" + k.ToString()))
                {
                    DropDownList ddList = (DropDownList)this.Master.FindControl("ContentPlaceHolder3").FindControl("wz_report").FindControl("PlaceHolder_group").FindControl("ddl_tot_field" + dr["field_sequence"].ToString() + "_" + dr["group_sequence"].ToString());
                    if (ddList != null)
                    {
                        if (ddList.Items.Count == 1)
                            populateNumericFields(ref ddList, cmbObjects.SelectedValue.Substring(cmbObjects.SelectedValue.IndexOf("@") + 1));
                        ddList.Text = objectId + dr["subtotal_field"].ToString() + "]"; // dsReport.Tables["p_report_grouping_subtotal"].Rows[k - 1]["subtotal_field"].ToString() + "]";

                        //DataRow dr1 = dt1.NewRow();
                        //dr1["af_row_id"] = dr["af_row_id"];
                        //dr1["rpt_group_id"] = k.ToString();
                        //dr1["group_sequence"] = dr["group_sequence"].ToString();
                        dr["subtotal_field"] = objectId + dr["subtotal_field"].ToString() + "]";
                        //dr1["field_sequence"] = dr["field_sequence"];
                        //dt1.Rows.Add(dr1);
                    }
                    idx++;
                }
            }
            //dt1 = null;

            //populateFieldsFromSelectedList(ref ddl_sort_details); //commented for phase-1
            if (lblMsgStep2.Text.Trim() != string.Empty && lblMsgStep2.Text.Contains("$"))
            {
                populateNumericFields(ref ddl_grtot_field1, lblMsgStep2.Text.Substring(lblMsgStep2.Text.IndexOf("$") + 1));
                populateNumericFields(ref ddl_grtot_field2, lblMsgStep2.Text.Substring(lblMsgStep2.Text.IndexOf("$") + 1));
                populateNumericFields(ref ddl_grtot_field3, lblMsgStep2.Text.Substring(lblMsgStep2.Text.IndexOf("$") + 1));
            }
            //sort details

            #region commented for phase-1
            //dt1 = dsReport.Tables["step3_report_grouping_sort_details"];
            //foreach (DataRow dr in dsReport.Tables["p_report_grouping_sort_details"].Rows)
            //{
            //    DataRow dr1 = dt1.NewRow();
            //    dr1["af_row_id"] = dr["af_row_id"];
            //    ddl_sort_details.Text = objectId + dr["sort_detail_field"].ToString() + "]";
            //    dr1["sort_detail_field"] = objectId + dr["sort_detail_field"].ToString() + "]";

            //    ddl_sort_order.Text = dr["sort_detail_order"].ToString();
            //    dr1["sort_detail_order"] = dr["sort_detail_order"].ToString(); 
            //    dt1.Rows.Add(dr1);
            //}
            //dt1 = null;
            #endregion

            //grand total
            //dt1 = dsReport.Tables["step3_report_grouping_grand_total"];
            foreach (DataRow dr in dsReport.Tables["p_report_grouping_grand_total"].Rows)
            {
                //DataRow dr1 = dt1.NewRow();
                //dr1["af_row_id"] = dr["af_row_id"];
                if (dr["attribute_sequence"].ToString() == "1")
                    ddl_grtot_field1.Text = objectId + dr["grand_total_field"].ToString() + "]";
                else if (dr["attribute_sequence"].ToString() == "2")
                    ddl_grtot_field2.Text = objectId + dr["grand_total_field"].ToString() + "]";
                else if (dr["attribute_sequence"].ToString() == "3")
                    ddl_grtot_field3.Text = objectId +  dr["grand_total_field"].ToString() + "]";

                //dr1["attribute_sequence"] = dr["attribute_sequence"].ToString();
                dr["grand_total_field"] = objectId + dr["grand_total_field"].ToString() + "]";
                //dt1.Rows.Add(dr1);
            }
            //dt1 = null;

            //Step 3
            //createDataTable(3, ref dsReport);
            //dt1 = dsReport.Tables["step4_report_details"];
            foreach (DataRow dr in dsReport.Tables["p_report_header_footer"].Rows)
            {
                //DataRow dr1 = dt1.NewRow();
                //dr1["af_row_id"] = dr["af_row_id"];
                txtRepTitle.Text = dr["rpt_title"].ToString();
                //dr1["rpt_title"] = dr["rpt_title"].ToString();
                
                txtHeaderText.Text = dr["rpt_head_text"].ToString();
                //dr1["rpt_head_text"] = dr["rpt_head_text"].ToString();
                
                txtFooterText.Text = dr["rpt_foot_text"].ToString();
                //dr1["rpt_foot_text"] = dr["rpt_foot_text"].ToString();
                
                chkDisplayLogo.Checked = Convert.ToBoolean(dr["rpt_logo"].ToString());
                //dr1["rpt_logo"] = dr["rpt_logo"].ToString();

                chkDisplayDate.Checked = Convert.ToBoolean(dr["rpt_date"].ToString());
                //dr1["rpt_date"] = dr["rpt_date"].ToString();

                chkDisplayPageNum.Checked = Convert.ToBoolean(dr["rpt_page_no"].ToString());
                //dr1["rpt_page_no"] = dr["rpt_page_no"].ToString();

                //dt1.Rows.Add(dr1);
            }
            //dt1 = null;

            LoadEditPage LEP = new LoadEditPage();
            txt_owner_id.Text = LEP.GetUserIDFromAfrowid(owner_id.Value);
            LEP = null;
            imgSelectEnableDisable();
            Session["report_ds"] = dsReport;

            //GlobalValues.dsAudit = dsReport; //Commanded by 'Imran Gani' on 24/02/2012, to avoid GlobalValues.dsAufit.
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("setData" + " : Error : " + ex.Message);
        }
        return true;
    }

    private void imgSelectEnableDisable()
    {
        if (lstFields1.Items.Count == 0)
        {
            imgSelect1.Enabled = false;
            imgSelectAll1.Enabled = false;
            imgUnselect1.Enabled = true;
            imgUnselectAll1.Enabled = true;
            imgUp1.Enabled = true;
            imgDown1.Enabled = true;
        }
        else if (lstSelectedFields1.Items.Count == 0)
        {
            imgSelect1.Enabled = true;
            imgSelectAll1.Enabled = true;
            imgUnselect1.Enabled = false;
            imgUnselectAll1.Enabled = false;
            imgUp1.Enabled = false;
            imgDown1.Enabled = false;
        }
        else
        {
            imgSelect1.Enabled = true;
            imgSelectAll1.Enabled = true;
            imgUnselect1.Enabled = true;
            imgUnselectAll1.Enabled = true;
            imgUp1.Enabled = true;
            imgDown1.Enabled = true;
        }
    }

    private string getFieldCaption(string LiValue)
    {
        string sCaption = "";
        try
        {
            if (dsReport != null)
            {
                if (dsReport.Tables.Contains("p_sy_report_att"))
                {
                    DataTable dtAtt = dsReport.Tables["p_sy_report_att"];

                    if (dtAtt != null)
                    {
                        string sAttribId = LiValue.Substring(LiValue.IndexOf("].[") + 3, LiValue.Length - 1 - (LiValue.IndexOf("].[") + 3));
                        string sObjectId = LiValue.Substring(1, LiValue.IndexOf("]") - 1);
                        DataRow[] dr = dtAtt.Select("rpt_id='" + hf_af_row_id1.Value + "' and object_id = '" + sObjectId + "' and attrib_id = '" + sAttribId + "'");

                        if (dr.Length != 0)
                        {
                            sCaption = dr[0]["caption"].ToString();
                        }
                    }
                }
            }
        }

        catch (Exception ex)
        {
            LogWriter.WriteLog(this.Title + " : Error : " + ex.Message);
        }
        return sCaption;
    }

    private string getReportId()
    {
        string sReportId = "1";

        try
        {
            string sTemp = hdd.GetColumnValue("Select max(rpt_id) from sy_report");
            if (sTemp != "")
                sReportId = Convert.ToString(Convert.ToInt16(sTemp) + 1);
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("getReportId : Error : " + ex.Message);
            return "1";
        }
        return sReportId;
    }

    protected void imgSelectAll_Click(object sender, ImageClickEventArgs e)
    {
        populateListBox(lstSelectedFields1, "SA"); //populateFields("", lstSelectedFields);
        lblFieldsMsg1.Text = "";
        imgUnselect1.Enabled = true;
        imgUnselectAll1.Enabled = true;
        imgUp1.Enabled = true;
        imgDown1.Enabled = true;
        if (lstFields1.Items.Count == 0)
        {
            imgSelect1.Enabled = false;
            imgSelectAll1.Enabled = false;
        }
    }

    protected void imgUnselectAll_Click(object sender, ImageClickEventArgs e)
    {
        populateListBox(lstFields1, "DS"); //populateFields("", lstFields);
        imgSelect1.Enabled = true;
        imgSelectAll1.Enabled = true;
        if (lstSelectedFields1.Items.Count == 0)
        {
            imgUnselect1.Enabled = false;
            imgUnselectAll1.Enabled = false;
            imgUp1.Enabled = false;
            imgDown1.Enabled = false;
        }
    }

    private void populateListBox(ListBox Fields, string selectAllFlag)
    {
        if (cmbObjects.SelectedIndex == -1) return;

        string sSql = "Select object_id from sy_obj where object_id='" + cmbObjects.SelectedValue.Substring(cmbObjects.SelectedValue.IndexOf("@") + 1) + "'";
        dtObj = hdd.GetDataTable(sSql);
        if (dtObj.Rows.Count == 0)
            populateFieldsFromQuery(Fields, selectAllFlag);
        else
            populateFields("", Fields, selectAllFlag);
    }

    private string getCustodianFilter(string sTableName)
    {
        string sCustodian = "";
        try
        {
            string sSql = "select custodian_filter from sy_usr where af_row_id='" + Session["user_afrowid"].ToString() + "'";
            string sTemp = hdd.GetColumnValue(sSql);
            if (Session["userid"].ToString() == "afadmin")
            {
                sCustodian = "";
            }
            else if (sTemp.ToLower() == "ar" || Session["user_afrowid"].ToString() == "650a333596bbf348" || sTemp.Trim() == "")
            {
                ////sCustodian = Tablename + ".created_by != 'e51e0327224a2eb9'";
                //sCustodian = "[" + sTableName + "].created_by <> 'e51e0327224a2eb9'";
                // Added by srivatsan on June 15 2009 for owner id field
                sCustodian = "[" + sTableName + "].owner_id <> 'e51e0327224a2eb9'";
            }
            else if (sTemp.ToLower() == "mr")
            {
                //sCustodian = "[" + sTableName + "].created_by='" + Session["user_afrowid"].ToString() + "'";//sCustodian = "created_by='" + Session["user_afrowid"].ToString() + "'";
                // Added by srivatsan on June 15 2009 for owner id field
                sCustodian = "[" + sTableName + "].owner_id='" + Session["user_afrowid"].ToString() + "'";//sCustodian = "created_by='" + Session["user_afrowid"].ToString() + "'";
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("getCustodianFilter : Error : " + ex.Message);
        }
        return sCustodian;
    }

    private string getSql()
    {
        BuildParameters BP = new BuildParameters();
        string sSql = "";
        try
        {
            if (dsReport.Tables["p_sy_report"].Rows[0]["rpt_base_object"].ToString().ToLower() == "sql")
            {
                string sSqlId = dsReport.Tables["p_sy_report_obj"].Rows[0]["object_id"].ToString();
                sSql = getPredefinedSQL(sSqlId);
            }
            else
            {
                string sTableName = getObjectName(dsReport.Tables["p_sy_report_obj"].Rows[0]["object_id"].ToString());
                string sFieldName = getFieldNames(dsReport.Tables["p_sy_report_att"], sTableName);
                if (sFieldName != "")
                    sSql = "Select " + sFieldName + " from " + sTableName;
                sSql = sSql + " where 1=1";
            }
            sSql = BP.ReplaceVariablesinQueries(sSql); // Added by 'Imran Gani' on 20-Nov-12, to handle system variables.
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("getSql : Error : " + ex.Message);
        }
        return sSql;
    }

    private string getObjectName(string ObjectId)
    {
        HDDatabase hdd = new HDDatabase(Session["dbcon"].ToString());
        string sObjectName = hdd.GetColumnValue("Select object_table from sy_obj where object_id = '" + ObjectId + "'");
        return sObjectName;
    }

    private string getPredefinedSQL(string SQL_id)
    {
        HDDatabase hdd = new HDDatabase(Session["dbcon"].ToString());
        string sSQL = "";
        //string sSQL = hdd.GetColumnValue("Select report_base_sql from sy_report_sql where report_base_id=" + SQL_id);
        DataRow drR = hdd.GetTableRow("Select report_base_sql from sy_report_sql where report_base_id=" + SQL_id);
        if (drR != null)
        {
            //decode added by Sampath on 27-Apr-2012
            //CommonFunctions.decodeData(drR);
            sSQL = drR["report_base_sql"].ToString();
        }
        drR = null;
        Hashtable hsParam = new Hashtable();
        hsParam = getParameters("$", ref hsParam, sSQL);
        hsParam = getParameters("#", ref hsParam, sSQL);
        if ((sSQL.Contains("$") || sSQL.Contains("#")) && !IsPostBack)
        {
            //DrawParameterTable(ref hsParam);
            //lbFF.Visible = false;
            //ddlFileFormat.Visible = false;
            //lnkExport.Visible = false;
            //lnkPrint.Enabled = false;
            sSQL = "";
            hsParam = null;
        }
        else
            sSQL = ReplaceParameters(sSQL);
        return sSQL;
    }

    private string ReplaceParameters(string SQL)
    {
        Hashtable hsParam = new Hashtable();
        hsParam = getParameters("$", ref hsParam, SQL);
        hsParam = getParameters("#", ref hsParam, SQL);
        foreach (string sParam in hsParam.Keys)
        {
            if (sParam.StartsWith("#") && sParam.EndsWith("#"))
                SQL = SQL.Replace(sParam, GetLocalizedDateTime(sParam));
            else
                SQL = SQL.Replace(sParam, Request.Form["ctl00$ContentPlaceHolder3$wz_Report$txt_" + sParam]);
        }
        return SQL;
    }

    private string GetLocalizedDateTime(string sParam)
    {
        string sRet = "";
        try
        {
            sRet = Request.Form["ctl00$ContentPlaceHolder3$wz_Report$txt_" + sParam];
            #region Old Code commmented by 'Imran Gani' on 28-Feb-2014, for locale support
            //Localization li = new Localization();
            //DateTime dt = DateTime.Parse(sRet, li.getUserCulture());
            //sRet = dt.ToString();
            //li = null;
            #endregion
            DateTime dt = DateTime.Parse(sRet, MBLocalization.getCultureInfo(HttpContext.Current.Session["userlocale"].ToString()));
            sRet = dt.ToString();

        }

        catch (Exception Ex)
        {
            LogWriter.WriteLog("ReplaceDateTime : Error : " + Ex.Message);
            //sRet = Request.Form["ctl00$ContentPlaceHolder3$wz_Report$txt_" + sParam];
        }
        return sRet;
    }

    private string getUTCHours(string sUTC_Offset)
    {
        string sHours = "+0";
        try
        {
            if (sUTC_Offset != "")
            {
                if (sUTC_Offset.IndexOf(".") != -1)
                    sHours = sUTC_Offset.Substring(0, sUTC_Offset.IndexOf('.'));
                else
                    sHours = sUTC_Offset.Trim();

                sHours = sHours.Replace("+", "").Replace("-", "");

                if (sUTC_Offset.StartsWith("-"))
                    sHours = "-" + sHours;
                else
                    sHours = "+" + sHours;
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("getUTCHours : Error : " + ex.Message);
            return "+0";
        }
        return sHours;
    }

    private string getUTCMinutes(string sUTC_Offset)
    {
        string sMinutes = "+0";
        try
        {
            if (sUTC_Offset != "")
            {
                sMinutes = sUTC_Offset.Substring(sUTC_Offset.IndexOf('.') + 1, sUTC_Offset.Length - sUTC_Offset.IndexOf('.') - 1);

                sMinutes = sMinutes.Replace("+", "").Replace("-", "");

                if (sUTC_Offset.StartsWith("-"))
                    sMinutes = "-" + sMinutes;
                else
                    sMinutes = "+" + sMinutes;
            }
        }

        catch (Exception ex)
        {
            LogWriter.WriteLog("getUTCMinutes : Error : " + ex.Message);
            return "+0";
        }
        return sMinutes;
    }

    private string getDTSQL(string ObjectName, string FieldName, string sHours, string sMinutes)
    {
        string sDateAdd = "";
        try
        {
            if (sMinutes != "")
                sDateAdd = "dateadd(mi, " + sMinutes + ", [" + ObjectName + "].[" + FieldName + "])";
            if (sHours != "")
            {
                if (sDateAdd == "")
                    sDateAdd = "dateadd(hh, " + sHours + ", [" + ObjectName + "].[" + FieldName + "])";
                else
                    sDateAdd = "dateadd(hh, " + sHours + "," + sDateAdd + ")";
            }
        }

        catch (Exception ex)
        {
            LogWriter.WriteLog("getDTSQL : Error : " + ex.Message);
            return FieldName;
        }
        return sDateAdd;
    }

    private string getUserIdSQL(string FieldName, string ObjectName)
    {
        string sUserSQL = "";
        try
        {
            sUserSQL = "(SELECT user_id AS " + FieldName + " from sy_usr as usr where (usr.af_row_id=" + ObjectName + "." + FieldName + ")) as " + FieldName + " ,";
        }

        catch (Exception ex)
        {
            LogWriter.WriteLog("getUserIdSQL : Error : " + ex.Message);
            sUserSQL = FieldName;
        }

        return sUserSQL;
    }

    private string getFieldNames(DataTable dtAttribute, string sObjectName)
    {
        string sFields = "";
        //DynamicDisplayI DDI = new DynamicDisplayI();
        //string sUTC_Offset = DDI.getUserSetting("sy_usr", "time_zone", "sy_timezone", "utc_offset", "timezone_id");

        //string sHrs = getUTCHours(sUTC_Offset);
        //string sMins = getUTCMinutes(sUTC_Offset);

        //HDDatabase hdd = new HDDatabase(Session["dbcon"].ToString());
        foreach (DataRow dr in dtAttribute.Rows)//Select("", "attrib_sequence asc")
        {
            string sAttrib_id = dr["attrib_id"].ToString();
            //if (sAttrib_id.ToLower() == "created_by" || sAttrib_id.ToLower() == "modified_by")
            //{
            //    sFields += getUserIdSQL(sAttrib_id, sObjectName);
            //}
            //else
            //{
            //    DataRow drMas_Det = hdd.GetTableRow("select * from sy_obj_mas_detail where master_obj='" + dr["object_id"].ToString() + "' and attrib_id = '" + sAttrib_id + "'");
            //    if (drMas_Det != null)
            //    {
            //        sAttrib_id = drMas_Det["display_att"].ToString();
            //    }
                //string sObject_name = getObjectName(dr["object_id"].ToString());
            //    string sDatatype = hdd.GetColumnValue("select attrib_data_type from sy_obj_att where object_id='" + hdd.GetColumnValue("select af_row_id from sy_obj where object_id='" + dr["object_id"].ToString() + "'") + "' and attrib_id = '" + sAttrib_id + "'");
            //    Localization li = new Localization();
            //    string sFormat = li.getDateTimeFormat();
            //    li = null;
            //    if (sDatatype == "DT")
            //    {
            //        string sDateAdd = getDTSQL(sObject_name, sAttrib_id, sHrs, sMins);
            //        sFields = sFields + sDateAdd + " as [" + sAttrib_id + "], ";
            //    }
            //    else
                    sFields = sFields + " [" + sObjectName + "].[" + sAttrib_id + "],"; //+ "] as [" + dr["caption"].ToString() + "], " ;
            //}
        }
        
        sFields = sFields.Trim();

        if (sFields.EndsWith(","))
            sFields = sFields.Trim(',');
        
        //if (sFields.EndsWith(","))
        //    sFields = sFields + "[" + sObjectName + "]." + "created_by as mb_c_by ";
        //else
        //    sFields = sFields + "," + "[" + sObjectName + "]." + "created_by as mb_c_by ";

            //sFields = sFields.Remove(sFields.Length - 1, 1);
        return sFields;
    }

    private string getReportProperties(string FieldName)
    {
        string sReportName = "";
        if (dsReport.Tables["p_sy_report"] != null)
        {
            sReportName = dsReport.Tables["p_sy_report"].Rows[0][FieldName].ToString();
        }
        return sReportName;
    }

    private void openReport()
    {
        if (fillInputData(ref dsReport))
        {
            if (Session["report_ds"] == null)
                Session.Add("report_ds", dsReport);
            else
                Session["report_ds"] = dsReport;
        }
        string popupScript = "<script language='javascript'>" +
            "(window.open('Report.aspx','ReportWindow'," +
            "'menubar=no,resizable=yes,scrollbars=yes," +
            "')||window).focus();" + "</script>";//height=600,width=800,top=50,left=100
        ClientScript.RegisterClientScriptBlock(imgNewWindow.GetType(), "ReportWindow", popupScript);
    }

    protected void imgNewWindow_Click(object sender, ImageClickEventArgs e)
    {
        //switch (wz_Report.ActiveStepIndex)
        //{
        //    case 0:
        //        break;
        //    case 1:
        //        if (cmbObjects.Text == "--Select an Object--")
        //        {
        //            lblGroupMsg.Text = "Please select an object";
        //            wz_Report.ActiveStepIndex = 1;
        //        }
        //        else if (lstSelectedFields1.Items.Count == 0)
        //        {
        //            //if (rbPredefinedObjects.Checked)
        //            //{
        //            //    DataRow dr = hdd.GetTableRow("select * from sy_report_sql where report_base_id=" + cmbObjects.SelectedItem.Value);
        //            //    if (dr != null)
        //            //    {
        //            //        if (!dr["report_base_sql"].ToString().Contains("$") && !dr["report_base_sql"].ToString().Contains("#"))
        //            //        {
        //            //            lblFieldsMsg1.Text = "Please select atleast one field to be displayed in the report";
        //            //            wz_Report.ActiveStepIndex = 1;
        //            //        }
        //            //        else
        //            //            openReport();
        //            //    }
        //            //}
        //            //else
        //            //{
        //            //    lblFieldsMsg1.Text = "Please select atleast one field to be displayed in the report";
        //            //    wz_Report.ActiveStepIndex = 1;
        //            //}
        //        }
        //        else
        //        {
        //            //FillSelectedFields();
        //            openReport();
        //        }
        //        break;
        //    case 2:
        //    case 3:
        //        openReport();
        //        break;
        //}
    }

    protected void btnFinish_Click(object sender, EventArgs e)
    {
        try
        {
            SaveData();
            wz_Report_CancelButtonClick(sender, e);
        }
        catch (Exception Ex)
        {
            LogWriter.WriteLog("btnFinish_Click : Error : " + Ex.Message);
        }
    }

    private void FillSelectedFields()
    {
        populateListBox(lstSelectedFields1, null); //populateFields("", lstSelectedFields);
        imgUnselect1.Enabled = true;
        imgUnselectAll1.Enabled = true;
        imgUp1.Enabled = true;
        imgDown1.Enabled = true;
        if (lstFields1.Items.Count == 0)
        {
            imgSelect1.Enabled = false;
            imgSelectAll1.Enabled = false;
        }
    }

    private void SaveDataforFinish()
    {
        if (fillInputData(ref dsReport))
        {

            if (IsEdit)
            {
                SaveData();
            }
            else
            {
                string sOperation = "INSERT";
                Master objMaster = new Master();

                if (!objMaster.ProcessOperation(dsPageInfo, dsReport, sOperation))
                    lblMessage.Text = objMaster.ErrorMessage;
            }
        }
        //deleteReport();        

        if (Session["ReportInput"] != null)
            Session.Remove("ReportInput");

        Response.Redirect(Session["RedirectLocation"].ToString(),false);
    }

    protected void ddlFileFormat_SelectedIndexChanged(object sender, EventArgs e)
    {
        //if (ddlFileFormat.SelectedIndex != 0)
        //    lnkExport.Enabled = true;
        //else
        //    lnkExport.Enabled = false;
    }

    private void Print()
    {
        try
        {
            if (m_streams == null || m_streams.Count == 0)
                return;
            PrintDocument printDoc = new PrintDocument();
            PrinterSettings ps = new PrinterSettings();

            if (printDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                ps.PrinterName = printDialog1.PrinterSettings.PrinterName;
                ps.Copies = printDialog1.PrinterSettings.Copies;
                ps.DefaultPageSettings.Color = printDialog1.PrinterSettings.DefaultPageSettings.Color;
                ps.DefaultPageSettings.Landscape = printDialog1.PrinterSettings.DefaultPageSettings.Landscape;
                ps.DefaultPageSettings.Margins = printDialog1.PrinterSettings.DefaultPageSettings.Margins;
                ps.DefaultPageSettings.PaperSize = printDialog1.PrinterSettings.DefaultPageSettings.PaperSize;
                ps.DefaultPageSettings.PaperSource = printDialog1.PrinterSettings.DefaultPageSettings.PaperSource;
                ps.DefaultPageSettings.PrinterResolution = printDialog1.PrinterSettings.DefaultPageSettings.PrinterResolution;
                ps.DefaultPageSettings.PrinterSettings = printDialog1.PrinterSettings.DefaultPageSettings.PrinterSettings;
                ps.Duplex = printDialog1.PrinterSettings.Duplex;
                ps.FromPage = printDialog1.PrinterSettings.FromPage;
                ps.MaximumPage = printDialog1.PrinterSettings.MaximumPage;
                ps.MinimumPage = printDialog1.PrinterSettings.MinimumPage;
                ps.PrintFileName = printDialog1.PrinterSettings.PrintFileName;
                ps.PrintRange = printDialog1.PrinterSettings.PrintRange;
                ps.PrintToFile = printDialog1.PrinterSettings.PrintToFile;
                ps.ToPage = printDialog1.PrinterSettings.ToPage;

                printDoc.PrinterSettings = ps;

                if (!printDoc.PrinterSettings.IsValid)
                {
                    string msg = String.Format("Can't find printer \"{0}\".", printDialog1.PrinterSettings.PrinterName);
                    return;
                }
                printDoc.PrintPage += new PrintPageEventHandler(PrintPage);
                printDoc.Print();
            }
        }

        catch (Exception ex)
        {
            LogWriter.WriteLog("Print : Error : " + ex.Message);
        }
    }

    private Stream CreateStream(string name, string fileNameExtension, Encoding encoding, string mimeType, bool willSeek)
    {
        Stream stream = null;
        try
        {
            stream = new FileStream(name + "." + fileNameExtension,
                FileMode.Create);
            m_streams.Add(stream);
        }

        catch (Exception ex)
        {
            LogWriter.WriteLog("CreateStream : Error : " + ex.Message);
        }
        return stream;
    }

    /// <summary>
    /// Export the given report as an EMF (Enhanced Metafile) file.
    /// </summary>
    private void Export(Microsoft.Reporting.WebForms.LocalReport report, string PageWidth, float PageHeight, float MarginTop, float MarginLeft, float MarginRight, float MarginBottom)
    {
        try
        {
            StringBuilder deviceInfosb = new StringBuilder();
            deviceInfosb.Append("<DeviceInfo>");
            deviceInfosb.Append("<OutputFormat>EMF</OutputFormat>");
            deviceInfosb.Append(string.Format("<PageWidth>{0}in</PageWidth>", PageWidth));
            deviceInfosb.Append(string.Format("<PageHeight>{0}in</PageHeight>", PageHeight));
            deviceInfosb.Append(string.Format("<MarginTop>{0}in</MarginTop>", MarginTop));
            deviceInfosb.Append(string.Format("<MarginLeft>{0}in</MarginLeft>", MarginLeft));
            deviceInfosb.Append(string.Format("<MarginRight>{0}in</MarginRight>", MarginRight));
            deviceInfosb.Append(string.Format("<MarginBottom>{0}in</MarginBottom>", MarginBottom));
            deviceInfosb.Append(string.Format("</DeviceInfo>"));
            string deviceInfo = deviceInfosb.ToString();
            Microsoft.Reporting.WebForms.Warning[] warnings;
            m_streams = new List<Stream>();
            //Warning[] warnings;
            //string[] streamids;
            //string mimeType;
            //string encoding;
            //string filenameExtension;
            //report.Render("Image", null, out mimeType, out encoding, out filenameExtension, out streamids, out warnings);
            report.Render("Image", deviceInfo, CreateStream, out warnings);
            foreach (Stream stream in m_streams)
            {
                stream.Position = 0;
            }
        }

        catch (Exception ex)
        {
            LogWriter.WriteLog("Export : Error : " + ex.Message);
        }
    }

    /// <summary>
    /// Handler for PrintPageEvents
    /// </summary>
    private void PrintPage(object sender, PrintPageEventArgs ev)
    {
        try
        {
            System.Drawing.Imaging.Metafile pageImage = new System.Drawing.Imaging.Metafile(m_streams[m_currentPageIndex]);
            ev.Graphics.DrawImage(pageImage, ev.PageBounds);
            m_currentPageIndex++;
            ev.HasMorePages = (m_currentPageIndex < m_streams.Count);
        }

        catch (Exception ex)
        {
            LogWriter.WriteLog("PrintPage : Error : " + ex.Message);
        }
    }

    protected void Page_SaveStateComplete(object sender, EventArgs e)
    {
        //try
        //{
        //    if (bExport)
        //    {
        //        if (ddlFileFormat.SelectedIndex != 0)
        //        {
        //            ReportPrintHelper oPrint = new ReportPrintHelper();
        //            switch (ddlFileFormat.SelectedValue)
        //            {
        //                case "Excel":
        //                    //oPrint.ExportReport(ref rptViewer, EXPORT_TYPE.TYPE_XLS, Context, true, HttpContext.Current.Session["ReportWidth"].ToString());
        //                    break;
        //                case "PDF":
        //                   // oPrint.ExportReport(ref rptViewer, EXPORT_TYPE.TYPE_PDF, Context, true, HttpContext.Current.Session["ReportWidth"].ToString());
        //                    break;
        //            }
        //            oPrint = null;
        //            ddlFileFormat.SelectedValue = "";
        //            bExport = false;
        //        }
        //    }
        //}
        //catch (Exception ex)
        //{
        //    LogWriter.WriteLog("Page_SaveStateComplete : Error : " + ex.Message);
        //}
    }
    
    protected void lnkPrint_Click(object sender, EventArgs e)
    {
        try
        {
            //if (ddlFileFormat.SelectedIndex == 0)
            //{
            //    lblmessage2.Text = "Please choose a file format";
            //    lblmessage2.Visible = true;
            //    ddlFileFormat.Focus();
            //    return;
            //}            
            //if (File.Exists(Server.MapPath(".") + "\\report\\" + hf_af_row_id1.Value + ".xml"))
            //{
            //    if (txtRepName.Text.Trim() == "")
            //        reportViewer.Report.Load(Server.MapPath(".") + "\\report\\" + hf_af_row_id1.Value + ".xml", "New Report");
            //    else
            //        reportViewer.Report.Load(Server.MapPath(".") + "\\report\\" + hf_af_row_id1.Value + ".xml", txtRepName.Text);
            //}
            //if (ddlFileFormat.SelectedItem.Text.ToLower() == "pdf")
            //    reportViewer.Report.RenderToFile(Server.MapPath(".") + "\\report\\" + hf_af_row_id1.Value + ".pdf", FileFormatEnum.PDF);
            //else if (ddlFileFormat.SelectedItem.Text.ToLower() == "excel")
            //    reportViewer.Report.RenderToFile(Server.MapPath(".") + "\\report\\" + hf_af_row_id1.Value + ".xls", FileFormatEnum.Excel);
            //MemoryStream ms = new MemoryStream();
            //reportViewer.Report.RenderToStream(ms, FileFormatEnum.Text);
            //Print();
            //ms.Flush();
            //ms.Close();
            //ms = null;
            wz_Report_CancelButtonClick(sender, e);
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("lnkPrint_Click : Error: " + ex.Message);
        }

        //try
        //{
        //    Microsoft.Reporting.WebForms.LocalReport report = reportViewer.Report;
        //    Export(report, HttpContext.Current.Session["ReportWidth"].ToString() /*dReportWidth*/, 8.27f, 0.3f, 0.3f, 0.3f, 0.3f);//Export(report, 11.69f, 8.27f, 0f, 0f, 0f, 0f);
        //    m_currentPageIndex = 0;

        //    Print(); foreach (Stream s in m_streams)
        //    {
        //        s.Close();
        //    }
        //}

        //catch (Exception ex)
        //{
        //    LogWriter.WriteLog("lnkPrint_Click : Error : " + ex.Message);
        //}
    }

    private Hashtable getParameters(string sChar, ref Hashtable hsParam, string sSql)
    {
        try
        {
            int iPos = 0;
            while (iPos < sSql.Length & iPos != -1)
            {
                string sParam = "";
                iPos = sSql.IndexOf(sChar,iPos);
                if (iPos != -1)
                {
                    int iEndPos = sSql.IndexOf(sChar, iPos + 1);
                    if (iEndPos == -1)
                        iEndPos = sSql.Length - iPos;
                    else
                        iEndPos = iEndPos - (iPos - 1);
                    sParam = sSql.Substring(iPos, iEndPos);
                    sParam = sParam.TrimEnd('\'');
                    if (!hsParam.Contains(sParam))
                    {
                        if (sChar == "$")
                            hsParam.Add(sParam, "'0'");
                        else if (sChar == "#")
                            hsParam.Add(sParam, "'" + DateTime.Now.ToShortDateString() + "'");
                    }
                    iPos = iPos + iEndPos;
                }
            }
        }
        catch (Exception Ex)
        {
            LogWriter.WriteLog("getParameters : Error : " + Ex.Message);
        }
        return hsParam;
    }

    private void DrawParameterTable(ref Hashtable hsParam)
    {
        try
        {
            if (hsParam.Count > 0)
            {
                DynamicDisplayI DDI = new DynamicDisplayI();
                HtmlTableCell ht = (HtmlTableCell)DDI.FindControl(this.Controls, "td_param");
                DDI = null;
                if (ht != null)
                {
                    HtmlTable htTable = new HtmlTable();
                    htTable.CellSpacing = 1;
                    htTable.CellPadding = 2;
                    htTable.Attributes.Add("runat", "server");
                    HtmlTableRow htr = new HtmlTableRow();
                    HtmlTableCell htc = new HtmlTableCell();
                    htr.Attributes.Add("class", "Grid_Header");
                    htc = new HtmlTableCell();
                    htc.InnerText = "Parameter   ";
                    htr.Cells.Add(htc);
                    htc = new HtmlTableCell();
                    htc.InnerText = "Value";
                    htr.Cells.Add(htc);
                    htTable.Rows.Add(htr);
                    foreach (string sParam in hsParam.Keys)
                    {
                        htr = new HtmlTableRow();
                        htc = new HtmlTableCell();
                        htr.Attributes.Add("class", "controlFont");
                        htc.InnerText = sParam.Replace("$", "").Replace("#", "") + "   ";
                        htr.Cells.Add(htc);
                        htc = new HtmlTableCell();
                        TextBox txt = new TextBox();
                        txt.ID = "txt_" + sParam;
                        //txt.Width = Unit.Parse("100");
                        htc.Controls.Add(txt);
                        htr.Cells.Add(htc);
                        htTable.Rows.Add(htr);
                    }
                    ht.Controls.Add(htTable);
                }
            }
        }

        catch (Exception Ex)
        {
            LogWriter.WriteLog("DrawParameterTable : Error : " + Ex.Message);
        }
    }

    private void SetParameter(ref Hashtable hsParam)
    {
        try
        {
            DynamicDisplayI DDI = new DynamicDisplayI();
            foreach (string sParam in hsParam.Keys)
            {
                TextBox txt = (TextBox)DDI.FindControl(this.Controls, "txt_" + sParam);
                if (txt != null)
                {
                    txt.Text = Request.Form["ctl00$ContentPlaceHolder3$wz_Report$txt_" + sParam];
                }
            }
            DDI = null;
        }

        catch (Exception Ex)
        {
            LogWriter.WriteLog("SetParameter : Error : " + Ex.Message);
        }
    }

    protected void btn_Generate_Click(object sender, EventArgs e)
    {
        try
        {
            ImageButton newWindow = (ImageButton)this.wz_Report.FindControl("HeaderContainer$imgNewWindow1");
            newWindow.Visible = false;
            generateReport(false, "");
            //if (generateReportXML(dsReport))
            //{
            //    if (File.Exists(Server.MapPath(".") + "\\report\\" + hf_af_row_id1.Value + ".xml"))
            //        reportViewer.Report.Load(Server.MapPath(".") + "\\report\\" + hf_af_row_id1.Value + ".xml", txtRepName.Text);
            //    else
            //        LogWriter.WriteLog("btn_Generate_Click: Error: Report file is not found");
            //}
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("btn_Generate_Click : Error : " + ex.Message);
        }
    }

    private string makeOLEDBConnectionString(string sqlConn)
    {
        string oledbConn = "";
        //Provider=SQLOLEDB;Persist Security Info=False;User ID=sa;Password=sa;Initial Catalog=TEST;Data Source=CSNSYS114\SQLEXPRESS
        //Data Source="CSNSYS114\SQLEXPRESS";User Id="Sam-003";Password="Sam-003_123";Initial Catalog="Sam-003"
        try
        {
            oledbConn = "Provider=SQLOLEDB;Persist Security Info=False;" + sqlConn.Replace("\"", "");
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("makeOLEDBConnectionString : Error : " + ex.Message);
        }
        return oledbConn;
    }

    private int calculateWidth(ref Hashtable hsT, string obj_name)
    {
        int totalwidth = 0;
        try
        {
            hsT.Clear();
            DataTable dt = hdd.GetDataTable("select af_row_id, attrib_id, isnull(attrib_size,0) as attrib_size from sy_obj_att where object_id='" + obj_name + "' order by attrib_seq");
            foreach (DataRow dr in dt.Rows)
            {
                totalwidth += Convert.ToInt32(dr["attrib_size"].ToString());
                hsT.Add(dr["af_row_id"], dr["attrib_size"]);
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("calculateWidth : Error: " + ex.Message);
        }
        return totalwidth;
    }

    private void fillSelectedValues(ref DataTable dt)
    {
        try
        {
            for (int k = 0; k < lstSelectedFields1.Items.Count; k++)
            {
                ListItem li = lstSelectedFields1.Items[k];
                Label lbl = (Label)this.Master.FindControl("ContentPlaceHolder3").FindControl("wz_report").FindControl("lbl_caption_" + li.Value);
                TextBox txtBox = (TextBox)this.Master.FindControl("ContentPlaceHolder3").FindControl("wz_report").FindControl("txt_" + li.Value);
                DropDownList dd1 = (DropDownList)this.Master.FindControl("ContentPlaceHolder3").FindControl("wz_report").FindControl("dd_" + li.Value + "_bold");
                DropDownList dd2 = (DropDownList)this.Master.FindControl("ContentPlaceHolder3").FindControl("wz_report").FindControl("dd_" + li.Value + "_wwrap");
                DataRow dr = dt.NewRow();
                dr["af_row_id"] = "";
                dr["attrib_id"] = li.Value;
                dr["caption"] = txtBox.Text;
                dr["is_bold"] = dd1.Text.ToLower() == "yes" ? "true" : "false";
                dr["is_wrap"] = dd2.Text.ToLower() == "yes" ? "true" : "false";
                dt.Rows.Add(dr);
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("fillSelectedValues : Error: " + ex.Message);
        }
    }

    private string getLogo()
    {
        string logopath = "";
        try
        {
            if (HttpContext.Current.Session["company_afrowid"] != null)
            {
                DirectoryInfo di = new DirectoryInfo(HttpContext.Current.Server.MapPath(".") + "\\Images\\CustomLogo");
                FileInfo[] fis = di.GetFiles(HttpContext.Current.Session["company_afrowid"].ToString() + "*");
                if (fis.Length > 0)
                {
                    logopath = "images/CustomLogo/" + fis[0].Name + "";
                }
                else//if another user in the same company logs out
                {
                    if (HttpContext.Current.Session["hasCustomLogo"] != null)
                    {
                        string fName = ""; string ext = "";
                        security s = new security();
                        s.createCustomLogo(ref fName, ref ext);
                        logopath = "images/CustomLogo/" + HttpContext.Current.Session["company_afrowid"] + ext;
                    }
                }
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("getLogo : Error: " + ex.Message);
        }
        return logopath;
    }

    private int getLength(string inputStr)
    {
        int strLen = 10;
        try
        {
            strLen = (inputStr.Length * 150);
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("getLength : Error: " + ex.Message);
        }
        return strLen;
    }

    private string getCSSContent()
    {
        string sCSSContent = "";
        StreamReader sr = null;
        try
        {
            string sFilePath = HttpContext.Current.Server.MapPath(".") + @"\App_Themes\" + HttpContext.Current.Session["theme"].ToString() + "\\" + HttpContext.Current.Session["theme"].ToString().ToLower().Replace("theme", "") + ".css";

            if (File.Exists(sFilePath))
            {
                sr = File.OpenText(sFilePath);
                sCSSContent = sr.ReadToEnd();
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("getCSSContent : Error: " + ex.Message);
        }
        finally
        {
            if (sr != null)
            {
                sr.Close();
                sr.Dispose();
            }
        }
        return sCSSContent;
    }

    private string getCSSClass(string CSSContent, string ClassName)
    {
        string sCSSClass = "";
        try
        {
            int iStart = 0;
            int iEnd = 0;
            if (CSSContent.Contains(ClassName))
            {
                iStart = CSSContent.IndexOf(ClassName);
                iEnd = CSSContent.IndexOf("}", iStart);
                sCSSClass = CSSContent.Substring(iStart + ClassName.Length, iEnd - iStart - ClassName.Length);
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("getCSSClass : Error: " + ex.Message);
        }
        return sCSSClass;
    }

    private string getCSSPropertyValue(string ClassName, string Property)
    {
        string sValue = "";
        try
        {
            string sCSSContent = getCSSContent();
            if (sCSSContent != "")
            {
                string sCSSClass = getCSSClass(sCSSContent, ClassName);
                if (sCSSClass != "")
                {
                    int iStart = 0;
                    int iEnd = 0;

                    if (sCSSClass.Contains(Property))
                    {
                        iStart = sCSSClass.IndexOf(Property);
                        iStart = sCSSClass.IndexOf(":", iStart);
                        iStart = iStart + 1;
                        iEnd = sCSSClass.IndexOf(";", iStart + 1);
                        sValue = sCSSClass.Substring(iStart, iEnd - iStart);
                    }
                }
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("getCSSPropertyValue : Error: " + ex.Message);
        }
        return sValue;
    }

    private Hashtable getCSSProperies(string ClassName)
    {
        Hashtable hsStyle = new Hashtable();
        try
        {
            string sValue = getCSSPropertyValue(ClassName, "background-color");
            if (sValue != "")
                hsStyle.Add("BackgroundColor", sValue);
            if (getCSSPropertyValue(ClassName, "FONT-WEIGHT").Trim().ToLower() == "bold")
                hsStyle.Add("FontWeight", "-1");
            else
                hsStyle.Add("FontWeight", "false");
            string sFontSize = getCSSPropertyValue(ClassName, "FONT-SIZE").Trim().ToLower().Replace("px", "");
            if (sFontSize == "") sFontSize = "8";
            hsStyle.Add("FontSize", sFontSize);
            sValue = getCSSPropertyValue(ClassName, "COLOR").Trim();
            if (sValue != "")
                hsStyle.Add("Color", sValue);
            sValue = getCSSPropertyValue(ClassName, "text-align").Trim();
            if (sValue == "")
                sValue = "Center";
            else
                sValue = sValue.Substring(0, 1).ToUpper() + sValue.Substring(1, sValue.Length - 1);
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("getCSSProperies : Error : " + ex.Message);
            hsStyle = null;
        }
        return hsStyle;
    }

    private Hashtable getFieldLengthForQuery(string sqlQry, string objectId, Hashtable hsDT)
    {
        Hashtable hsWidth = new Hashtable();
        DataTable dtTmp = new DataTable();
        try
        {
            if (!sqlQry.ToLower().Contains("distinct"))
                dtTmp = hdd.GetDataTable("select top 100 " + sqlQry.Substring(6, sqlQry.Length - 6));
            else
                dtTmp = hdd.GetDataTable(sqlQry);
            foreach (ListItem li in lstSelectedFields1.Items)
            {
                string attrib_id = li.Text.Substring(li.Text.IndexOf("].[") + 3).TrimEnd(']');
                if (dtTmp.Columns.Contains(attrib_id))
                {
                    string width = "20";
                    //string colName = "[" + objectId + "].[" + dtTmp.Columns[attrib_id].ColumnName + "]";
                    if (dtTmp.Columns[attrib_id].MaxLength > 2000)
                        width = dtTmp.Columns[attrib_id].MaxLength.ToString();//hsWidth.Add(attrib_id, dtTmp.Columns[attrib_id].MaxLength);//colName
                    else if ((dtTmp.Columns[attrib_id].ColumnName.Length * 110) < 2000)
                        width = "20";//hsWidth.Add(attrib_id, 2000);//colName
                    else
                        width = dtTmp.Columns[attrib_id].ColumnName.Length.ToString();//hsWidth.Add(attrib_id, (dtTmp.Columns[attrib_id].ColumnName.Length * 110));//colName

                    //check the data
                    if (hsDT[attrib_id.ToLower()].ToString().ToLower() == "string")
                    {
                        DataRow[] drF = dtTmp.Select("len(" + attrib_id + ")>" + width, attrib_id + " desc");
                        if (drF.Length > 0)
                        {
                            if (drF[0][attrib_id].ToString().Length * 110 > Convert.ToInt32(width) * 110)
                                width = drF[0][attrib_id].ToString().Length.ToString();
                        }
                        drF = null;
                    }
                    hsWidth.Add(attrib_id, Convert.ToInt32(width) * 110);
                }
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("getFieldLengthForQuery : Error : " + ex.Message);
        }
        return hsWidth;
    }

    private int getFieldLengthForObject(string attrib_id, string object_id, string table_name)
    {
        int retLength = 2000;
        DataTable dtTmp = new DataTable();
        try
        {
            string qry = "select attrib_id,isNull(attrib_size,0)[attrib_size],attrib_name,attrib_data_type from sy_obj_att where ";
            qry += "object_id = (select af_row_id from sy_obj where object_id='" + object_id.Trim() + "') and ";
            if (attrib_id.IndexOf("].[") != -1)
                qry += "af_row_id='" + attrib_id.Substring(attrib_id.IndexOf("].[") + 3).TrimEnd(']') + "'";
            else
                qry += "af_row_id='" + attrib_id + "'";

            dtTmp = hdd.GetDataTable(qry);
            int dataLength = 0;
            if (dtTmp.Rows.Count > 0)
            {
                //Getting the Fields list with size and datatype
                int llength = 0;
                if (dtTmp.Rows[0]["attrib_data_type"].ToString() == "TX")
                {
                    llength = Convert.ToInt32(dtTmp.Rows[0]["attrib_size"].ToString());
                    if (llength == 0)
                        retLength = 2000;
                    else
                        retLength = llength * 110;
                }
                //check the max characters in the table

                string tQry = "select isnull(max(len([" + dtTmp.Rows[0]["attrib_id"].ToString() + "])),0)[max_length] from " + table_name;

                DataTable dt1 = hdd.GetDataTable(tQry);
                if (dt1.Rows.Count > 0)
                {
                    dataLength = Convert.ToInt32(dt1.Rows[0]["max_length"].ToString());
                    if (dataLength > 0)
                        retLength = dataLength * 110;
                }
                else if (dt1.Rows.Count == 0)
                {
                    tQry = "select isnull(max(datalength([" + dtTmp.Rows[0]["attrib_id"].ToString() + "])),0)[max_length] from " + table_name;
                    dt1 = hdd.GetDataTable(tQry);
                    if (dt1.Rows.Count > 0)
                    {
                        dataLength = Convert.ToInt32(dt1.Rows[0]["max_length"].ToString());
                        if (dataLength > 0)
                            retLength = dataLength * 110;
                    }
                }
                dt1 = null;

                //check the max characters in the attribute name
                llength = dtTmp.Rows[0]["attrib_name"].ToString().Length;
                if (((llength * 110) > retLength) || (dataLength == 0))
                    retLength = llength * 110;
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("getFieldLengthForObject : Error : " + ex.Message);
        }
        finally
        {
            dtTmp.Dispose();
            dtTmp = null;
        }
        return (retLength + 220);
    }

    private DataTable getBindList(string object_id)
    {
        DataTable dtRet = new DataTable();
        try
        {
            string qry = "select bind_table,control_id, control_attrib_id, IsNull(control_bind_id, '') as control_bind_id, bnd.af_row_id, bind_value, bind_text,isnull(bind_parameter,'') as bind_parameter ";
            qry += "from sy_pg_ctr pgctr,sy_bnd bnd where bnd.af_row_id = pgctr.control_bind_id and ";
            qry += "page_id = (select af_row_id from sy_pg where object_id='" + object_id + "') and ";
            qry += "IsNull(control_bind_id,'') not in ('', 'f496930dfe0b690f')";
            dtRet = hdd.GetDataTable(qry);
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("getBindList : Error : " + ex.Message);
        }
        return dtRet;
    }

    private DataTable getMasterDetail(string object_id)
    {
        DataTable dtRet = new DataTable();
        try
        {
            string qry = "select master_obj,display_att,attrib_id,attrib_name from sy_obj_mas_detail ";
            qry += "where object_id=(select af_row_id from sy_obj where object_id='" + object_id + "')";
            dtRet = hdd.GetDataTable(qry);
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("getMasterDetail : Error : " + ex.Message);
        }
        return dtRet;
    }

    private Hashtable getSqlDataTypes(string query)
    {
        Hashtable hsDt = new Hashtable();
        try
        {
            DataTable dtRet = new DataTable();
            if (!query.ToLower().Contains("distinct"))
                query = "select top 1 " + query.Substring(6, query.Length - 6);
            dtRet = hdd.GetDataTable(query);
            foreach (DataColumn dc in dtRet.Columns)
                hsDt.Add(dc.ColumnName.ToLower(), dc.DataType.Name);
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("getSqlDataTypes : Error : " + ex.Message);
        }
        return hsDt;
    }

    private bool checkData(string query)
    {
        bool retFlag = false;
        try
        {
            DataTable dtRet = new DataTable();
            if (!query.ToLower().Contains("distinct"))
                query = "select top 1 " + query.Substring(6, query.Length - 6);
            dtRet = hdd.GetDataTable(query);
            if (dtRet.Rows.Count > 0)
                retFlag = true;
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("checkData : Error : " + ex.Message);
        }
        return retFlag;
    }

    private void cancelClick()
    {
        try
        {
            HDDatabase HDD = new HDDatabase();
            dsReport = null;
            dsPageInfo = null;

            Session["report_ds"] = null;
            Session["FieldProperties"] = null;
            hiddenTmp.Value = "";
            hiddenGroupCnt.Value = "";
            Response.Redirect("DisplayGrid.aspx?mn=" + HDD.GetColumnValue("sy_mnu", "af_row_id", "pageset_id = '6421de320e189de8' and pageset_url = 'reportwizard_new.aspx'") + "&pgs_id=6421de320e189de8", false); // pageset_id and pgs_id=ps_report
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("cancelClick : Error : " + ex.Message);
        }
    }

    private Hashtable updateParameters(string sql, string param)
    {
        Hashtable hsParamNew = new Hashtable();
        try
        {
            BuildParameters bpObj = new BuildParameters();
            hsParamNew = bpObj.updateParameters(sql, param, Master.FindControl("ContentPlaceHolder3").FindControl("wz_report"), "");
            #region code commented
            /*
            Hashtable hsParam = new Hashtable();
            string sQueryId = cmbObjects.SelectedValue.Substring(cmbObjects.SelectedValue.IndexOf("@") + 1);
            if (param.Trim() == "")
            {
                getParameters("$", ref hsParam, sql);
                getParameters("#", ref hsParam, sql);
            }
            else
            {
                if (param.Trim().ToLower().StartsWith("parameters"))
                    param = param.Substring("parameters".Length + 1).Trim();

                foreach (string str1 in param.Split(','))
                {
                    if (str1.Trim() == "") continue;
                    if (str1.Trim() == "") continue;
                    if (str1.IndexOf("=") == -1)
                        hsParam.Add(str1.Trim(), getDefaultValue(str1.Substring(str1.IndexOf("]") + 1).Trim()));
                    else
                        hsParam.Add(str1.Substring(0, str1.IndexOf("=")).Trim(), str1.Substring(str1.IndexOf("=") + 1).Trim());
                }
            }
            int iCnt = 1;
            foreach (string key in hsParam.Keys)
            {
                DynamicDisplayI ddI = new DynamicDisplayI();
                if (param.Trim() != "")
                {

                    if (key.StartsWith("$") || key.StartsWith("#"))
                    {
                        //string ch = key.StartsWith("$") ? "$" : "#";
                        TextBox txt = (TextBox)ddI.FindControl(Master.FindControl("ContentPlaceHolder3").FindControl("wz_report").Controls, "txt_param_" + iCnt.ToString());
                        if (txt != null)
                        {
                            if (txt.Text.Trim() == "")
                                hsParamNew.Add(key, "'0'");
                            else
                                hsParamNew.Add(key, txt.Text);
                        }
                    }
                    else
                    {
                        string parName = key.Substring(0, key.LastIndexOf("["));
                        string par = key.Replace(parName,"").Replace("[", "").Replace("]", "");
                        string[] pars = par.Split('.');
                        DataTable dt = hdd.GetDataTable("select * from sy_pg_ctr where page_id=(select af_row_id from sy_pg where [page_table_name]='" + pars[0] + "') and control_attrib_id='" + pars[1] + "'");
                        if (dt.Rows.Count > 0)
                        {
                            //creating control based on control_html
                            //EM,DD,TA,AN,TB,CB,DDE,PW
                            switch (dt.Rows[0]["control_html"].ToString().ToUpper())
                            {
                                case "AN":
                                case "EM":
                                case "PW":
                                case "TA":
                                case "TB":
                                    TextBox txt = (TextBox)ddI.FindControl(Master.FindControl("ContentPlaceHolder3").FindControl("wz_report").Controls, "txt_" + key);
                                    if (txt != null)
                                    {
                                        HiddenField hf = (HiddenField)ddI.FindControl(Master.FindControl("ContentPlaceHolder3").FindControl("wz_report").Controls, "hf_" + key);
                                        if (hf != null)
                                        {
                                            if (hf.Value.Trim() == "")
                                            {
                                                if (txt.Text.Trim() == "")
                                                    hsParamNew.Add(key, "'0'");
                                                else
                                                {
                                                    if (txt.Text.Trim().StartsWith("'") && txt.Text.Trim().EndsWith("'"))
                                                        hsParamNew.Add(key, txt.Text.Trim());
                                                    else
                                                        hsParamNew.Add(key, "'" + txt.Text + "'");
                                                }
                                            }
                                            else
                                                hsParamNew.Add(key, "'" + hf.Value + "'");
                                        }
                                        else
                                        {
                                            if (txt.Text.Trim().StartsWith("'") && txt.Text.Trim().EndsWith("'"))
                                                hsParamNew.Add(key, txt.Text.Trim());
                                            else
                                            {
                                                if (txt.Text.Trim() != "")
                                                    hsParamNew.Add(key, "'" + txt.Text.Trim() + "'");
                                                else
                                                    hsParamNew.Add(key, "'0'");
                                            }
                                        }
                                    }
                                    break;
                                case "CB":
                                    CheckBox cb = (CheckBox)ddI.FindControl(Master.FindControl("ContentPlaceHolder3").FindControl("wz_report").Controls, "cb_" + key);
                                    if (cb != null)
                                        hsParamNew.Add(key, "'" +  cb.Checked.ToString() + "'");
                                    break;
                                case "DD":
                                case "DDE":
                                    DropDownList dd = (DropDownList)ddI.FindControl(Master.FindControl("ContentPlaceHolder3").FindControl("wz_report").Controls, "dd_" + key);
                                    if (dd != null)
                                    {
                                        if (dd.Text.Trim() == "")
                                            hsParamNew.Add(key, "'0'");
                                        else
                                            hsParamNew.Add(key, "'" + dd.Text + "'");
                                    }
                                    break;
                                case "DT":
                                case "DA":
                                    TextBox dadt = (TextBox)ddI.FindControl(Master.FindControl("ContentPlaceHolder3").FindControl("wz_report").Controls, "dt_" + key);
                                    if (dadt != null)
                                    {
                                        if (dadt.Text.Trim() == "")
                                            hsParamNew.Add(key, "'" + DateTime.Now.ToShortDateString() + "'");
                                        else
                                            hsParamNew.Add(key, "'" + dadt.Text + "'");
                                    }
                                    break;
                            }
                        }
                    }
                }
                else
                {
                    //string ch = key.StartsWith("$") ? "$" : "#";
                    TextBox txt = (TextBox)ddI.FindControl(Master.FindControl("ContentPlaceHolder3").FindControl("wz_report").Controls, "txt_param_" + iCnt.ToString());
                    if (txt != null)
                    {
                        if (txt.Text.Trim() == "")
                        {
                            if (key.StartsWith("$"))
                                hsParamNew.Add(key, "0");
                            else if (key.StartsWith("#"))
                                hsParamNew.Add(key, DateTime.Now.ToShortDateString());
                        }
                        else
                            hsParamNew.Add(key, "" + txt.Text + "");
                        iCnt++;
                    }   
                }
                ddI = null;
            }
            */
            #endregion
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("updateParameters : Error : " + ex.Message);
        }
        return hsParamNew;
    }

    /*
    private Hashtable updateParameters(string sql, string param)
    {
        Hashtable hsParamNew = new Hashtable();
        try
        {
            Hashtable hsParam = new Hashtable();
            string sQueryId = cmbObjects.SelectedValue.Substring(cmbObjects.SelectedValue.IndexOf("@") + 1);
            if (param.Trim() == "")
            {
                getParameters("$", ref hsParam, sql);
                getParameters("#", ref hsParam, sql);
            }
            else
            {
                if (param.Trim().ToLower().StartsWith("parameters"))
                    param = param.Substring("parameters".Length + 1).Trim();

                foreach (string str1 in param.Split(','))
                {
                    if (str1.Trim() == "") continue;
                    if (str1.Trim() == "") continue;
                    if (str1.IndexOf("=") == -1)
                        hsParam.Add(str1.Trim(), getDefaultValue(str1.Substring(str1.IndexOf("]") + 1).Trim()));
                    else
                        hsParam.Add(str1.Substring(0, str1.IndexOf("=")).Trim(), str1.Substring(str1.IndexOf("=") + 1).Trim());
                }
            }
            int iCnt = 1;
            foreach (string key in hsParam.Keys)
            {
                DynamicDisplayI ddI = new DynamicDisplayI();
                if (param.Trim() != "")
                {

                    if (key.StartsWith("$") || key.StartsWith("#"))
                    {
                        //string ch = key.StartsWith("$") ? "$" : "#";
                        TextBox txt = (TextBox)ddI.FindControl(Master.FindControl("ContentPlaceHolder3").FindControl("wz_report").Controls, "txt_param_" + iCnt.ToString());
                        if (txt != null)
                        {
                            if (txt.Text.Trim() == "")
                                hsParamNew.Add(key, "'0'");
                            else
                                hsParamNew.Add(key, txt.Text);
                        }
                    }
                    else
                    {
                        string parName = key.Substring(0, key.LastIndexOf("["));
                        string par = key.Replace(parName, "").Replace("[", "").Replace("]", "");
                        string[] pars = par.Split('.');
                        DataTable dt = hdd.GetDataTable("select * from sy_pg_ctr where page_id=(select af_row_id from sy_pg where [page_table_name]='" + pars[0] + "') and control_attrib_id='" + pars[1] + "'");
                        if (dt.Rows.Count > 0)
                        {
                            //creating control based on control_html
                            //EM,DD,TA,AN,TB,CB,DDE,PW
                            switch (dt.Rows[0]["control_html"].ToString().ToUpper())
                            {
                                case "AN":
                                case "EM":
                                case "PW":
                                case "TA":
                                case "TB":
                                    TextBox txt = (TextBox)ddI.FindControl(Master.FindControl("ContentPlaceHolder3").FindControl("wz_report").Controls, "txt_" + key);
                                    if (txt != null)
                                    {
                                        HiddenField hf = (HiddenField)ddI.FindControl(Master.FindControl("ContentPlaceHolder3").FindControl("wz_report").Controls, "hf_" + key);
                                        if (hf != null)
                                        {
                                            if (hf.Value.Trim() == "")
                                            {
                                                if (txt.Text.Trim() == "")
                                                    hsParamNew.Add(key, "'0'");
                                                else
                                                {
                                                    if (txt.Text.Trim().StartsWith("'") && txt.Text.Trim().EndsWith("'"))
                                                        hsParamNew.Add(key, txt.Text.Trim());
                                                    else
                                                        hsParamNew.Add(key, "'" + txt.Text + "'");
                                                }
                                            }
                                            else
                                                hsParamNew.Add(key, "'" + hf.Value + "'");
                                        }
                                        else
                                        {
                                            if (txt.Text.Trim().StartsWith("'") && txt.Text.Trim().EndsWith("'"))
                                                hsParamNew.Add(key, txt.Text.Trim());
                                            else
                                            {
                                                if (txt.Text.Trim() != "")
                                                    hsParamNew.Add(key, "'" + txt.Text.Trim() + "'");
                                                else
                                                    hsParamNew.Add(key, "'0'");
                                            }
                                        }
                                    }
                                    break;
                                case "CB":
                                    CheckBox cb = (CheckBox)ddI.FindControl(Master.FindControl("ContentPlaceHolder3").FindControl("wz_report").Controls, "cb_" + key);
                                    if (cb != null)
                                        hsParamNew.Add(key, "'" + cb.Checked.ToString() + "'");
                                    break;
                                case "DD":
                                case "DDE":
                                    DropDownList dd = (DropDownList)ddI.FindControl(Master.FindControl("ContentPlaceHolder3").FindControl("wz_report").Controls, "dd_" + key);
                                    if (dd != null)
                                    {
                                        if (dd.Text.Trim() == "")
                                            hsParamNew.Add(key, "'0'");
                                        else
                                            hsParamNew.Add(key, "'" + dd.Text + "'");
                                    }
                                    break;
                                case "DT":
                                case "DA":
                                    TextBox dadt = (TextBox)ddI.FindControl(Master.FindControl("ContentPlaceHolder3").FindControl("wz_report").Controls, "dt_" + key);
                                    if (dadt != null)
                                    {
                                        if (dadt.Text.Trim() == "")
                                            hsParamNew.Add(key, "'" + DateTime.Now.ToShortDateString() + "'");
                                        else
                                            hsParamNew.Add(key, "'" + dadt.Text + "'");
                                    }
                                    break;
                            }
                        }
                    }
                }
                else
                {
                    //string ch = key.StartsWith("$") ? "$" : "#";
                    TextBox txt = (TextBox)ddI.FindControl(Master.FindControl("ContentPlaceHolder3").FindControl("wz_report").Controls, "txt_param_" + iCnt.ToString());
                    if (txt != null)
                    {
                        if (txt.Text.Trim() == "")
                        {
                            if (key.StartsWith("$"))
                                hsParamNew.Add(key, "0");
                            else if (key.StartsWith("#"))
                                hsParamNew.Add(key, DateTime.Now.ToShortDateString());
                        }
                        else
                            hsParamNew.Add(key, "" + txt.Text + "");
                        iCnt++;
                    }
                }
                ddI = null;
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("updateParameters : Error : " + ex.Message);
        }
        return hsParamNew;
    }
    */
    
    private string getSqlAlignment(string fieldName, Hashtable hsDt)
    {
        string retAlign = "6";
        try
        {
            string fldName = fieldName;
            if (fieldName.IndexOf("].[") == -1)
                fldName = fieldName;
            else
                fldName = fieldName.Substring(fieldName.IndexOf("].[") + 3).TrimEnd(']');
            string tmp = hsDt[fldName.ToLower()].ToString();
            switch (tmp.ToLower())
            { 
                case "string":
                    retAlign = "6";
                    break;
                case "double":
                case "decimal":
                case "int16":
                case "int32":
                case "int64":
                    retAlign = "8";
                    break;
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("getSqlAlignment : Error : " + ex.Message);
        }
        return retAlign;
    }

    private string getSqlDataType(string fieldName, Hashtable hsDt)
    {
        string retType = "";
        try
        {
            string fldName = fieldName;
            if (fieldName.IndexOf("].[") == -1)
                fldName = fieldName;
            else
                fldName = fieldName.Substring(fieldName.IndexOf("].[") + 3).TrimEnd(']');
            retType = hsDt[fldName.ToLower()].ToString();
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("getSqlDataType : Error : " + ex.Message);
        }
        return retType;
    }

    private string checkSingleQuote(string parName, string inputVal, string qry)
    {
        string outVal = inputVal;
        try
        {
            if (qry.IndexOf(parName) != -1)
            {
                string tmp = qry.Substring(qry.IndexOf(parName) - 3, 3 + parName.Length);
                if (tmp.Contains("%") || tmp.Contains("'"))
                    outVal = inputVal.TrimStart('\'').TrimEnd('\'');
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("checkSingleQuote:Error:" + ex.Message);
        }
        return outVal;
    }

    private void setVisibleValue(bool value)
    { 
        try
        {
           // reportViewer.Visible = value;
            ddlExport.Visible = value;
            lblExport.Visible = value;
            lnkExport.Visible = value;
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("setVisibleValue:Error:" + ex.Message);
        }
    }

    private bool generateReport(bool exportFlag, string exportFormat)//Karthik on implementing reporting control change
    {
        reportViewer.Reset();//karthik to refresh the report, without this Logo, Date and page number will not show immidiate change in the preview.
        if (wz_Report.ActiveStepIndex < 5) return true;
        if (dsReport == null)
        {
            cancelClick();
            return false;
        }
        if (dsReport.Tables.Count == 0)
        {
            cancelClick();
            return false;
        }

        if (txtRepName.Text == "")
        {
            if (txtRepTitle.Text.Trim() != "")
                txtRepName.Text = txtRepTitle.Text;
            else
                txtRepName.Text = cmbObjects.SelectedItem.Text;
        }
        lbl_ReportName.Text = txtRepName.Text;
        bool IsExport = getExportValue();
        if (IsExport)
        {
            lblExport.Visible = true;
            ddlExport.Visible = true;
            lnkExport.Visible = true;

        }
        else
        {
            lblExport.Visible = false;
            ddlExport.Visible = false;
            lnkExport.Visible = false;
        }


        string sReportName = null;
        bool isGenerated = true;
        try
        {

            ImageButton newWindow = (ImageButton)this.wz_Report.FindControl("HeaderContainer$imgNewWindow1");
            newWindow.Visible = false;
            if (fillInputData(ref dsReport))
            {
                //added by Sampath on 10-Nov-2011 for Encoding
                //CommonFunctions.encodeData(dsReport);

                //imgNewWindow.Enabled = true;
                if (Session["ReportInput"] == null)
                    Session.Add("ReportInput", dsPageInfo);
                else
                    Session["ReportInput"] = dsPageInfo;

                string constr = Session["dbcon"].ToString();

                #region customized for implementing reporting control change
                string sSqlObjID = "Select af_row_id from sy_obj where object_id = '" + cmbObjects.SelectedValue.Substring(cmbObjects.SelectedValue.IndexOf('@') + 1) + "'";
                string sSqlColName = "Select attrib_id,af_row_id from sy_obj_att where object_id = '" + hdd.GetColumnValue(sSqlObjID).Trim() + "'";
                //string sSqlObjID = "Select attrib_id,attrib_name from sy_obj_att where object_id = '" + cmbObjects.SelectedValue.Substring(cmbObjects.SelectedValue.IndexOf('@') + 1) + "'";

                DataTable dtColNames = hdd.GetDataTable(sSqlColName);

                if (dsReport.Tables["p_sy_report_att"].Columns["attrib_name"] == null)
                {
                    DataColumn dCol = new DataColumn("attrib_name");
                    dsReport.Tables["p_sy_report_att"].Columns.Add(dCol);
                }

                foreach (DataRow dr in dsReport.Tables["p_sy_report_att"].Rows)
                {
                    DataRow[] drArr = dtColNames.Select("af_row_id='" + dr["attrib_id"] + "'");
                    if (drArr.Length > 0)
                    {
                        //dr["attrib_name"] = drArr[0]["attrib_id"].ToString();
                        dr["attrib_name"] = drArr[0]["attrib_id"].ToString();
                    }
                }

                #endregion


                string sSql = "";
                if (dsReport.Tables["p_sy_report"].Rows[0]["rpt_base_object"].ToString().ToLower() == "object")//implemented for Reporting Control Change
                    sSql = getSqlForObjects();
                else if (hiddenParam.Value == "P") //parameterized query
                {

                    string sSqlId = dsReport.Tables["p_sy_report_obj"].Rows[0]["object_id"].ToString();
                    //sSql = hdd.GetColumnValue("Select report_base_sql from sy_report_sql where report_base_id=" + sSqlId);
                    DataRow drR = hdd.GetTableRow("Select report_base_sql from sy_report_sql where report_base_id=" + sSqlId);
                    if (drR != null)
                    {
                        //decode added by Sampath on 27-Apr-2012
                        //CommonFunctions.decodeData(drR);
                        sSql = drR["report_base_sql"].ToString();
                    }
                    drR = null;
                    string sqlParam = "";

                    Hashtable hsParamNew = new Hashtable();
                    if (Session["param"] == null)
                        hsParamNew = updateParameters(sSql, sqlParam);
                    else
                        hsParamNew = (Hashtable)Session["param"];

                    if (hsParamNew.Count == 0)
                    {
                        createParameters();
                        hsParamNew = updateParameters(sSql, sqlParam);
                    }

                    //if default value is present then generate with default values

                    if (Session["showReport"] == null)
                    {
                        setVisibleValue(false);
                        return true;
                    }
                    else if (Convert.ToBoolean(Session["showReport"].ToString()) == false)
                    {
                        setVisibleValue(false);
                        return true;
                    }
                    else
                        setVisibleValue(true);

                    if (hsParamNew.Count > 0)
                    {
                        BuildParameters bpObj = new BuildParameters();
                        sSql = bpObj.makeSQL(hsParamNew, sSql);
                        bpObj = null;
                    }
                    //foreach (string sParam in hsParamNew.Keys)
                    //{
                    //    if (sqlParam.Trim() != "")
                    //    {
                    //        //string tmpP = "$" + sParam.Substring(0, sParam.LastIndexOf("[")).Replace("[", "").Replace("]", "") + "$";
                    //        //string outVal = checkSingleQuote(tmpP, hsParamNew[sParam].ToString(), sql);
                    //        //sql = sql.Replace(tmpP, outVal);//hsParamNew[sParam].ToString()
                    //        string tmpP = "$" + sParam.Substring(0, sParam.LastIndexOf("[")).Replace("[", "").Replace("]", "") + "$";
                    //        string outVal = checkSingleQuote(tmpP, hsParamNew[sParam].ToString(), sql);
                    //        sql = sql.Replace(tmpP, outVal);//hsParamNew[sParam].ToString()

                    //        tmpP = "#" + sParam.Substring(0, sParam.LastIndexOf("[")).Replace("[", "").Replace("]", "") + "#";
                    //        outVal = checkSingleQuote(tmpP, hsParamNew[sParam].ToString(), sql);
                    //        sql = sql.Replace(tmpP, outVal);//hsParamNew[sParam].ToString()
                    //    }
                    //    else
                    //        sql = sql.Replace(sParam, hsParamNew[sParam].ToString());
                    //}
                    hsParamNew = null;
                }
                else
                    sSql = getSql();

                sReportName = getReportProperties("rpt_name");
                if (sReportName == "") sReportName = getReportProperties("rpt_id");
                SqlDataSource1.ConnectionString = constr;
                SqlDataSource1.SelectCommand = sSql;

                MyRDLC mrdlc = new MyRDLC();                
                MemoryStream msReport = null;

                float dReportWidth = 8.0f;
                if (dsReport.Tables["p_sy_report"].Rows[0]["rpt_base_object"].ToString().ToLower() == "object")
                {
                    getDataFromSQLandFormat objData = new getDataFromSQLandFormat(sSql);
                    DataTable dt = objData.getData(ref dsReport);
                    //CommonFunctions.decodeData(dt); // Added by 'Imran Gani' on 29-Oct-12, to decode the datarow.
                    objData = null;
                    if (dt != null)
                    {
                        if (dsReport.Tables["p_sy_report_att"].Columns["temp_attrib_id"] == null)
                        {
                            DataColumn dCol = new DataColumn("temp_attrib_id");
                            dsReport.Tables["p_sy_report_att"].Columns.Add(dCol);
                            foreach (DataRow dr in dsReport.Tables["p_sy_report_att"].Rows)
                            {
                                dr["temp_attrib_id"] = dr["attrib_id"];
                            }
                        }

                        foreach (DataRow dr in dsReport.Tables["p_sy_report_att"].Rows)
                        {
                            dr["attrib_id"] = dr["attrib_name"];
                        }
                        MBFunctions MBF = new MBFunctions(); // Added by 'Imran Gani' on 03-Feb-2014, for currency conversion.
                        MBF.HandleCurrencyColumn(dt, dsReport.Tables["p_sy_report_att"].Rows[0]["object_id"].ToString());

                        if (exportFormat == "") //Added by 'Imran Gani' on 05-Nov-2012, to set Hyperlink property.
                            mrdlc.EnableHyperLink = LinkSet(dt, dsReport); //Added by 'Imran Gani' on 13/02/2012, to get Hyperlink column in dt.
                        exportType = exportFormat; // Added by 'Imran Gani' on 15-Oct-2013, (copied from Nithya for Handleing css properties in export option)
                        mrdlc.GenerateReportFromDataset(dsReport, ref msReport, ref dReportWidth, exportType);
                        reportViewer.LocalReport.DataSources.Clear();
                        reportViewer.LocalReport.DataSources.Add(new Microsoft.Reporting.WebForms.ReportDataSource("DataSet1", dt));
                        reportViewer.Visible = true;
                        reportViewer.LocalReport.DisplayName = sReportName;
                        reportViewer.LocalReport.LoadReportDefinition(msReport);
                        reportViewer.LocalReport.EnableExternalImages = true;
                        if (mrdlc.EnableHyperLink == true) //Added by 'Imran Gani' on 14/02/2012, for HyperLink properties setting.
                        {
                            reportViewer.LocalReport.EnableHyperlinks = true; //Added by 'Imran Gani' on 10/02/2012, to make active HyperLink.
                            //reportViewer.HyperlinkTarget = "_Blank"; //Added by 'Imran Gani' on 10/02/2012, to open a link in new tab.
                        }
                        reportViewer.LocalReport.Refresh();
                        msReport.Dispose();

                        //Test
                        if (dsReport.Tables["p_sy_report_att"].Columns["temp_attrib_id"] != null)
                        {
                            foreach (DataRow dr in dsReport.Tables["p_sy_report_att"].Rows)
                            {
                                dr["attrib_id"] = "[" + dr["object_id"] + "].[" + dr["temp_attrib_id"].ToString() + "]";
                            }
                            dsReport.Tables["p_sy_report_att"].Columns.Remove("temp_attrib_id");
                        }
                    }
                }
                else
                {
                    getDataFromSQLandFormat objData = new getDataFromSQLandFormat(sSql);
                    DataTable dt1 = objData.getData(ref dsReport);
                    //CommonFunctions.decodeData(dt1); // Added by 'Imran Gani' on 29-Oct-12, to decode the datarow.
                    objData = null;

                    foreach (DataRow dr in dsReport.Tables["p_sy_report_att"].Rows) // Added by 'Imran Gani' on 07-May-2014, to handle space in column name.
                    {
                        if (dt1.Columns[dr["caption"].ToString()] != null)
                            if (dt1.Columns[dr["caption"].ToString()].ColumnName.Contains(" "))
                                dt1.Columns[dr["caption"].ToString()].ColumnName = dr["attrib_id"].ToString();
                    }

                    if (dsPageInfo.Tables["Table"] != null)
                        dsPageInfo.Tables.Remove("Table");
                    dsPageInfo.Tables.Add(dt1.Copy());

                    if (dsReport.Tables["Table"] != null)
                        dsReport.Tables.Remove("Table");
                    dsReport.Tables.Add(dt1.Copy());

                    //foreach (DataRow dr in dsReport.Tables["p_sy_report_att"].Rows)
                    //{
                    //    //dr["attrib_id"] = dr["caption"];
                    //}

                    if (dt1.Columns.Contains("af_row_id") && exportFormat == "") //Added by 'Imran Gani' on 02/05/2012, to get Hyperlink column in dt.
                        mrdlc.EnableHyperLink = LinkSet(dt1, dsReport);
                    // Modified parameter by 'Imran Gani' on 15-Oct-2013, (copied from Nithya for Handleing css properties in export option)
                    mrdlc.GenerateReportFromDataset(dsReport, ref msReport, ref dReportWidth, exportType);
                    reportViewer.LocalReport.DataSources.Clear();
                    reportViewer.LocalReport.DataSources.Add(new Microsoft.Reporting.WebForms.ReportDataSource("DataSet1", dt1));
                    reportViewer.Visible = true;
                    reportViewer.LocalReport.DisplayName = sReportName;
                    reportViewer.LocalReport.LoadReportDefinition(msReport);
                    reportViewer.LocalReport.EnableExternalImages = true;
                    if (mrdlc.EnableHyperLink == true) //Added by 'Imran Gani' on 02/05/2012, for HyperLink properties setting.
                    {
                        reportViewer.LocalReport.EnableHyperlinks = true; //Added by 'Imran Gani' on 02/05/2012, to make active HyperLink.
                        //reportViewer.HyperlinkTarget = "_Blank"; //Added by 'Imran Gani' on 02/05/2012, to open a link in new tab.
                    }
                    reportViewer.LocalReport.Refresh();
                    dt1.Dispose();
                    dt1 = null;
                }
            }
            else
                exportFlag = false;
            //bool IsExport = getExportValue();
            #region export
            if (exportFlag)
            {
                Response.ClearContent();
                Response.ClearHeaders();
                Microsoft.Reporting.WebForms.Warning[] warnings;
                 
                string mimeType,strEncoding;
                string deviceInfo = "";
                string ext="";
                string[] streams;
                byte[] bytes;
                switch (exportFormat.ToUpper().Trim())
                {
                    case "XLS":
                        deviceInfo =
                        @"<DeviceInfo>
                        <OutputFormat>Excel</OutputFormat>
                        <PageWidth>8.5in</PageWidth>
                        <PageHeight>11in</PageHeight>
                        <MarginTop>0.25in</MarginTop>
                        <MarginLeft>0.25in</MarginLeft>
                        <MarginRight>0.25in</MarginRight>
                        <MarginBottom>0.25in</MarginBottom>
                        </DeviceInfo>";
                
                        bytes = reportViewer.LocalReport.Render("Excel", deviceInfo, out mimeType, out strEncoding, out ext, out streams, out warnings);
                        Response.Buffer = true;
                        Response.Clear();
                        Response.ContentType = mimeType;
                        Response.AddHeader("content-disposition", "attachment; filename=" + sReportName.Replace(" ", "_") + ".xls");
                        Response.BinaryWrite(bytes);
                        Response.Flush();
                        break;
                    case "PDF":
                        deviceInfo =
                        @"<DeviceInfo>
                        <OutputFormat>PDF</OutputFormat>
                        <PageWidth>8.5in</PageWidth>
                        <PageHeight>11in</PageHeight>
                        <MarginTop>0.25in</MarginTop>
                        <MarginLeft>0.25in</MarginLeft>
                        <MarginRight>0.25in</MarginRight>
                        <MarginBottom>0.25in</MarginBottom>
                        </DeviceInfo>";

                        bytes = reportViewer.LocalReport.Render("PDF", deviceInfo, out mimeType, out strEncoding, out ext, out streams, out warnings);
                        Response.Buffer = true;
                        Response.Clear();
                        Response.ContentType = mimeType;
                        Response.AddHeader("content-disposition", "attachment; filename=" + sReportName.Replace(" ", "_") + ".pdf");
                        Response.BinaryWrite(bytes);
                        Response.Flush();
                        break;
                    case "RTF":
                        deviceInfo =
                        @"<DeviceInfo>
                        <OutputFormat>RTF</OutputFormat>
                        <PageWidth>8.5in</PageWidth>
                        <PageHeight>11in</PageHeight>
                        <MarginTop>0.25in</MarginTop>
                        <MarginLeft>0.25in</MarginLeft>
                        <MarginRight>0.25in</MarginRight>
                        <MarginBottom>0.25in</MarginBottom> 
                        </DeviceInfo>";

                        bytes = reportViewer.LocalReport.Render("RTF", deviceInfo, out mimeType, out strEncoding, out ext, out streams, out warnings);
                        Response.Buffer = true;
                        Response.Clear();
                        Response.ContentType = mimeType;
                        Response.AddHeader("content-disposition", "attachment; filename=" + sReportName.Replace(" ", "_") + ".rtf");
                        Response.BinaryWrite(bytes);
                        Response.Flush();
                        break;
                    case "HTML":
                        deviceInfo =
                        @"<DeviceInfo>
                        <OutputFormat>HTML</OutputFormat>
                        <PageWidth>8.5in</PageWidth>
                        <PageHeight>11in</PageHeight>
                        <MarginTop>0.25in</MarginTop>
                        <MarginLeft>0.25in</MarginLeft>
                        <MarginRight>0.25in</MarginRight>
                        <MarginBottom>0.25in</MarginBottom>
                        </DeviceInfo>";

                        bytes = reportViewer.LocalReport.Render("HTML", deviceInfo, out mimeType, out strEncoding, out ext, out streams, out warnings);
                        Response.Buffer = true;
                        Response.Clear();
                        Response.ContentType = mimeType;
                        Response.AddHeader("content-disposition", "attachment; filename=" + sReportName.Replace(" ", "_") + ".htm");
                        Response.BinaryWrite(bytes);
                        Response.Flush();
                        break;
                    default:
                        deviceInfo =
                        @"<DeviceInfo>
                        <OutputFormat>Excel</OutputFormat>
                        <PageWidth>8.5in</PageWidth>
                        <PageHeight>11in</PageHeight>
                        <MarginTop>0.25in</MarginTop>
                        <MarginLeft>0.25in</MarginLeft>
                        <MarginRight>0.25in</MarginRight>
                        <MarginBottom>0.25in</MarginBottom>
                        </DeviceInfo>";

                        bytes = reportViewer.LocalReport.Render("Excel", deviceInfo, out mimeType, out strEncoding, out ext, out streams, out warnings);
                        Response.Buffer = true;
                        Response.Clear();
                        Response.ContentType = mimeType;
                        Response.AddHeader("content-disposition", "attachment; filename=" + sReportName.Replace(" ", "_") + ".xls");
                        Response.BinaryWrite(bytes);
                        Response.Flush();
                        break;
                }
            }
            #endregion
            //reportViewer.SizeToReportContent = true;
            //reportViewer.ShowRefreshButton = false;
            //reportViewer.ShowExportControls = false;
            //reportViewer.Height = Unit.Pixel(310);            
        }

        catch (Exception ex)
        {
            lblExport.Visible = false;
            ddlExport.Visible = false;
            lnkExport.Visible = false;
            imgNewWindow.Enabled = false;
            LogWriter.WriteLog("Error : " + ex.Message);
            Response.Redirect("Error.aspx?hc=r");
            return false;
        }
        return isGenerated;
        //--Commented to replace the component one control with asp.net report viewer control.
        #region Old Code for component one
        //if (wz_Report.ActiveStepIndex < 4) return true;

        //if (dsReport == null)
        //{
        //    cancelClick();
        //    return false;
        //}
        //if (dsReport.Tables.Count == 0)
        //{
        //    cancelClick();
        //    return false;
        //}

        //bool isGenerated = true;
        //XmlDocument xDoc = new XmlDocument();
        //int reportWidth = 10;
        //XmlElement xNode = null, xParent = null, xChild = null, xInnerChild = null;
        //Hashtable hsStyle = null;
        //Hashtable hsReportWidth = new Hashtable();
        //Hashtable hsDupFields = new Hashtable();
        //Hashtable hsFieldNames = new Hashtable();

        //try
        //{
        //    hsStyle = getCSSProperies(".Grid_Report_Header");
        //    reportViewer.BorderWidth = Unit.Point(1);
        //    reportViewer.BorderColor = System.Drawing.Color.FromName(hsStyle["BackgroundColor"].ToString());
        //    reportViewer.BackColor = System.Drawing.Color.White;
        //    reportViewer.NavigationBar.Style.BorderWidth = Unit.Point(1);
        //    reportViewer.NavigationBar.Style.BorderColor = System.Drawing.Color.FromName(hsStyle["BackgroundColor"].ToString());

        //    hsStyle = getCSSProperies(".Grid_Row1");
        //    string alColor = hsStyle["BackgroundColor"].ToString();
        //    reportViewer.NavigationBar.Style.BackColor = System.Drawing.Color.FromName(alColor);

        //    //reportViewer.NavigationBar.Style.Font.Size = FontUnit.Point(8);
        //    //reportViewer.NavigationBar.Style.CssClass = "controlFont";            
        //    hsStyle = null;

        //    XmlDeclaration xDec = xDoc.CreateXmlDeclaration("1.0", "utf-8", "yes");

        //    XmlElement rootNode = xDoc.CreateElement("Reports");
        //    xDoc.AppendChild(rootNode);

        //    XmlElement reportNode = xDoc.CreateElement("Report");

        //    #region Report Information
        //    DataTable dt = dsReport.Tables["p_sy_report"];
        //    if (dt.Rows.Count == 0)
        //    {
        //        xNode = xDoc.CreateElement("Name");
        //        xNode.InnerText = "New Report";
        //        reportNode.AppendChild(xNode);

        //        xParent = xDoc.CreateElement("ReportInfo");
        //        xChild = xDoc.CreateElement("Title");
        //        xChild.InnerText = "NOT SPECIFIED";
        //        xParent.AppendChild(xChild);
        //        reportNode.AppendChild(xParent);
        //    }
        //    else
        //    {
        //        xNode = xDoc.CreateElement("Name");
        //        if (txtRepName.Text.Trim() == "")
        //            xNode.InnerText = "New Report";
        //        else
        //            xNode.InnerText = txtRepName.Text;
        //        reportNode.AppendChild(xNode);

        //        xParent = xDoc.CreateElement("ReportInfo");
        //        xChild = xDoc.CreateElement("Title");
        //        if (txtRepTitle.Text.Trim() == "")
        //            xChild.InnerText = "NOT SPECIFIED";
        //        else
        //            xChild.InnerText = txtRepTitle.Text;
        //        xParent.AppendChild(xChild);
        //        reportNode.AppendChild(xParent);
        //    }
        //    #endregion

        //    Localization loc = new Localization();
        //    string sDateTimeFormatString = loc.getDateTimeFormat();
        //    string sDateFormatString = loc.getDateFormat();
        //    loc = null;

        //    #region Assigning DataSource - object or query
        //    if (Session["dbcon"] == null)
        //    {
        //        LogWriter.WriteLog("generateReport : Error : connection string is empty");
        //        return false;
        //    }

        //    DataTable dtTmp = null;
        //    string sql = "", cols = "", tabName = "";

        //    if (lblReportSrc.Text.ToLower() == "object")
        //    {
        //        dtTmp = hdd.GetDataTable("select [object_name]obj_name, object_table from sy_obj where [object_id]='" + cmbObjects.SelectedValue.Substring(cmbObjects.SelectedValue.IndexOf("@") + 1) + "'");
        //        if (dtTmp.Rows.Count > 0)
        //            tabName = dtTmp.Rows[0]["object_table"].ToString();
        //    }
        //    else if (lblReportSrc.Text.ToLower() == "sql")
        //    {
        //        string sqlParam = "";
        //        dtTmp = hdd.GetDataTable("select report_base_sql, report_base_param from sy_report_sql where report_base_id='" + cmbObjects.SelectedValue.Substring(cmbObjects.SelectedValue.IndexOf("@") + 1) + "'");
        //        if (dtTmp.Rows.Count > 0)
        //        {
        //            sql = dtTmp.Rows[0]["report_base_sql"].ToString();
        //            sqlParam = dtTmp.Rows[0]["report_base_param"].ToString();
        //        }
        //        else
        //        {
        //            LogWriter.WriteLog("generateReport : Error : Table/Query object is empty");
        //            return false;
        //        }

        //        if (hiddenParam.Value == "P") //parameterized query
        //        {

        //            Hashtable hsParamNew = new Hashtable();
        //            if (Session["param"] == null)
        //                hsParamNew = updateParameters(sql, sqlParam);
        //            else
        //                hsParamNew = (Hashtable)Session["param"];

        //            if (hsParamNew.Count == 0)
        //            {
        //                createParameters();
        //                hsParamNew = updateParameters(sql, sqlParam);
        //            }
        //            //if default value is present then generate with default values

        //            if (Session["showReport"] == null)
        //            {
        //                setVisibleValue(false);
        //                return true;
        //            }
        //            else if (Convert.ToBoolean(Session["showReport"].ToString()) == false)
        //            {
        //                setVisibleValue(false);
        //                return true;
        //            }
        //            else
        //                setVisibleValue(true);

        //            if (hsParamNew.Count > 0)
        //            {
        //                BuildParameters bpObj = new BuildParameters();
        //                sql = bpObj.makeSQL(hsParamNew, sql);
        //                bpObj = null;
        //            }
        //            //foreach (string sParam in hsParamNew.Keys)
        //            //{
        //            //    if (sqlParam.Trim() != "")
        //            //    {
        //            //        //string tmpP = "$" + sParam.Substring(0, sParam.LastIndexOf("[")).Replace("[", "").Replace("]", "") + "$";
        //            //        //string outVal = checkSingleQuote(tmpP, hsParamNew[sParam].ToString(), sql);
        //            //        //sql = sql.Replace(tmpP, outVal);//hsParamNew[sParam].ToString()
        //            //        string tmpP = "$" + sParam.Substring(0, sParam.LastIndexOf("[")).Replace("[", "").Replace("]", "") + "$";
        //            //        string outVal = checkSingleQuote(tmpP, hsParamNew[sParam].ToString(), sql);
        //            //        sql = sql.Replace(tmpP, outVal);//hsParamNew[sParam].ToString()

        //            //        tmpP = "#" + sParam.Substring(0, sParam.LastIndexOf("[")).Replace("[", "").Replace("]", "") + "#";
        //            //        outVal = checkSingleQuote(tmpP, hsParamNew[sParam].ToString(), sql);
        //            //        sql = sql.Replace(tmpP, outVal);//hsParamNew[sParam].ToString()
        //            //    }
        //            //    else
        //            //        sql = sql.Replace(sParam, hsParamNew[sParam].ToString());
        //            //}
        //            hsParamNew = null;
        //        }
        //    }
        //    dtTmp = null;

        //    dt = dsReport.Tables["p_sy_report_att"];
        //    if (!IsEdit && dt != null)
        //    {
        //        if (dt.Columns.Contains("af_row_id"))
        //        {
        //            if (dt.Select("af_row_id <> '' Or af_row_id is not null").Length != dt.Rows.Count)
        //                dt.Rows.Clear();
        //        }
        //        else
        //            dt.Rows.Clear();
        //    }
        //    if (dt == null)
        //    {
        //        collect_step_values(1);
        //        dt = dsReport.Tables["p_sy_report_att"];
        //    }
        //    if (dt != null)
        //    {
        //        if (dt.Rows.Count == 0)
        //        {
        //            dsReport = collect_step_values(1);
        //            dt = dsReport.Tables["p_sy_report_att"];
        //        }

        //        if (dt.Rows.Count != lstSelectedFields1.Items.Count)
        //        {
        //            if (!IsEdit)
        //                dt.Rows.Clear();
        //            collect_step_values(1);
        //        }
        //        else if (dt.Rows.Count == lstSelectedFields1.Items.Count)
        //        {
        //            DataTable dtR = dt.Clone();
        //            for (int iCount = 0; iCount < lstSelectedFields1.Items.Count; iCount++)
        //            {
        //                ListItem li = lstSelectedFields1.Items[iCount];
        //                DataRow[] drF = dt.Select("attrib_id='" + li.Value + "'");
        //                if (drF.Length > 0)
        //                    dtR.ImportRow(drF[0]);
        //                else
        //                {
        //                    if (li.Value.IndexOf("].[") != -1)
        //                    {
        //                        drF = dt.Select("attrib_id='" + li.Value.Substring(li.Value.IndexOf("].[") + 3).Replace("]", "") + "'");
        //                        if (drF.Length > 0)
        //                            dtR.ImportRow(drF[0]);
        //                    }
        //                }
        //                drF = null;
        //            }
        //            dt.Rows.Clear();
        //            dt.Merge(dtR);
        //            dtR.Rows.Clear();
        //            dtR = null;
        //        }
        //        if (dt.Rows.Count == 0)
        //            collect_step_values(1);

        //        if (lblReportSrc.Text.ToLower() == "object")
        //        {
        //            DataTable dtBind = getBindList(cmbObjects.SelectedValue.Substring(cmbObjects.SelectedValue.IndexOf("@") + 1));
        //            DataTable dtMasDetail = getMasterDetail(cmbObjects.SelectedValue.Substring(cmbObjects.SelectedValue.IndexOf("@") + 1));

        //            foreach (DataRow dr in dt.Rows)
        //            {
        //                DataRow[] drT = dt.Select("caption='" + dr["caption"].ToString() + "'");
        //                if (drT.Length > 1)
        //                {
        //                    if (hsDupFields.ContainsKey(dr["caption"].ToString()))
        //                        hsDupFields[dr["caption"].ToString()] = Convert.ToInt32(hsDupFields[dr["caption"].ToString()]) + 1;
        //                    else
        //                        hsDupFields.Add(dr["caption"].ToString(), 1);
        //                }
        //                else
        //                    hsDupFields.Add(dr["caption"].ToString(), 1);
        //                drT = null;

        //                string caption = setCaption(lblReportSrc.Text, dr["attrib_id"].ToString(), dr["caption"].ToString()) + hsDupFields[dr["caption"].ToString()];
        //                hsFieldNames.Add(dr["attrib_id"].ToString(), caption);

        //                if (caption.Trim() == "")
        //                {
        //                    DataRow[] drF = dtMasDetail.Select("attrib_id='" + dr["attrib_id"].ToString().Substring(dr["attrib_id"].ToString().IndexOf("].[") + 3).TrimEnd(']') + "'");
        //                    if (drF.Length > 0)
        //                        caption = drF[0]["display_att"].ToString();
        //                    drF = null;
        //                }

        //                if (dr["attrib_id"].ToString().IndexOf("].[") == -1)
        //                {
        //                    cols += "[" + getAttribId(lblReportSrc.Text, dr["attrib_id"].ToString()) + "] as [" + caption + "],";
        //                }
        //                else
        //                {
        //                    string attrib_id = getAttribId(lblReportSrc.Text, dr["attrib_id"].ToString().Substring(dr["attrib_id"].ToString().IndexOf("].[") + 3).TrimEnd(']'));

        //                    if (dtMasDetail.Rows.Count > 0)
        //                    {
        //                        DataRow[] drF = dtMasDetail.Select("attrib_id='" + attrib_id.Trim() + "'");
        //                        string tName = hdd.GetColumnValue("select object_table from sy_obj where object_id='" + drF[0]["master_obj"].ToString() + "'");
        //                        cols += "(select top 1 " + drF[0]["display_att"].ToString() + " from " + tName + " where af_row_id=" + tabName + "." + attrib_id + ") as [" + caption + "],";
        //                        dtMasDetail.Rows.Clear();
        //                    }
        //                    else if (dtBind.Select("control_attrib_id='" + attrib_id + "'").Length > 0)
        //                    {
        //                        DataRow[] drF = dtBind.Select("control_attrib_id='" + attrib_id + "'");
        //                        //(select top 1 emp_lname + '  ' + emp_fname from ap_emp as A where A.emp_id=ap_emp.report_emp_id)as report_emp_id
        //                        if (drF[0]["bind_table"].ToString().IndexOf(",") == -1)
        //                            cols += "(select top 1 " + drF[0]["bind_text"].ToString() + " from " + drF[0]["bind_table"].ToString() + " As BT1 where BT1.[" + drF[0]["bind_value"].ToString() + "]=[" + tabName + "].[" + attrib_id + "]) as [" + caption + "],";
        //                        else//multi tables in bind_table
        //                        {
        //                            //(select top 1 customer_name from bu_customer A,bu_program B where A.customer_id = B.customer_id and A.customer_id=2)
        //                            string[] tables = drF[0]["bind_table"].ToString().Split(',');
        //                            cols += "(select top 1 " + drF[0]["bind_text"].ToString() + " from ";
        //                            string tmpStr = "";
        //                            Hashtable hsTmp = new Hashtable();
        //                            for (int i = 0; i < tables.Length; i++)
        //                            {
        //                                tmpStr += tables[i] + " As BT" + (i + 1) + ",";
        //                                hsTmp.Add(tables[i], "BT" + (i + 1));
        //                            }
        //                            cols += tmpStr.TrimEnd(',');
        //                            tmpStr = drF[0]["bind_parameter"].ToString();
        //                            if (tmpStr.Trim() != "")
        //                            {
        //                                foreach (string key in hsTmp.Keys)
        //                                    tmpStr = tmpStr.Replace(key, hsTmp[key].ToString());
        //                                cols += " where " + tmpStr + " and " + drF[0]["bind_value"].ToString() + "=[" + tabName + "].[" + attrib_id + "]) as [" + caption + "],";
        //                            }
        //                            else
        //                                cols += " where " + drF[0]["bind_value"].ToString() + "=[" + tabName + "].[" + attrib_id + "]) as [" + caption + "],";
        //                            hsTmp = null;
        //                        }
        //                    }
        //                    //createdby/modifiedby conversion
        //                    else if (attrib_id.ToLower() == "created_at" || attrib_id.ToLower() == "modified_at")
        //                    {
        //                        DataTable dtZone = new DataTable();
        //                        string tQry = "select utc_offset from sy_timezone where timezone_id = (select time_zone from sy_usr where af_row_id='" + Session["user_afrowid"].ToString() + "')";
        //                        dtZone = hdd.GetDataTable(tQry);
        //                        if (dtZone.Rows.Count > 0)
        //                        {
        //                            string offset = dtZone.Rows[0]["utc_offset"].ToString();
        //                            if (offset.IndexOf(".") != -1)
        //                            {
        //                                int mins = Convert.ToInt32(offset.Substring(offset.IndexOf(".") + 1));
        //                                int hrs = Convert.ToInt32(offset.Substring(0, offset.IndexOf(".")));
        //                                cols += "(select dateadd(minute," + mins.ToString() + ",dateadd(hour," + hrs.ToString() + "," + attrib_id + "))) as [" + caption + "],";
        //                            }
        //                            else
        //                                cols += "(select dateadd(hour," + offset + "," + attrib_id + ")) as [" + caption + "],";
        //                        }
        //                        else
        //                            cols += "[" + attrib_id + "] as [" + caption + "],";
        //                        dtZone = null;
        //                    }
        //                    //created/modified timezone conversion
        //                    else if (attrib_id.ToLower() == "created_by" || attrib_id.ToLower() == "modified_by" || attrib_id.ToLower() == "owner_id")
        //                    {
        //                        string objName = dr["attrib_id"].ToString().Substring(0, dr["attrib_id"].ToString().IndexOf("]")).Replace("[", "").Replace("]", "");
        //                        cols += "(" + getOwnerName(attrib_id, objName) + ") as [" + caption + "],";
        //                    }
        //                    else
        //                        cols += "[" + attrib_id + "] as [" + caption + "],";
        //                }
        //                caption = "";
        //            }
        //            sql = "select " + cols.TrimEnd(',') + " from " + tabName;
        //            dtBind = null;
        //        }
        //    }
        //    else
        //    {
        //        if (lblReportSrc.Text.ToLower() == "object")
        //        {
        //            DataTable dtBind = getBindList(cmbObjects.SelectedValue.Substring(cmbObjects.SelectedValue.IndexOf("@") + 1));
        //            DataTable dtMasDetail = getMasterDetail(cmbObjects.SelectedValue.Substring(cmbObjects.SelectedValue.IndexOf("@") + 1));

        //            //cols += "[" + getAttribId(lblReportSrc.Text, li.Value.Substring(li.Value.IndexOf("].[") + 3).TrimEnd(']')) + "] as [" + caption + "],";
        //            foreach (ListItem li in lstSelectedFields1.Items)
        //            {
        //                DataRow[] drT = dt.Select("caption='" + li.Value.ToString() + "'");
        //                if (drT.Length > 1)
        //                {
        //                    if (hsDupFields.ContainsKey(li.Value.ToString()))
        //                        hsDupFields[li.Value.ToString()] = Convert.ToInt32(hsDupFields[li.Value.ToString()]) + 1;
        //                    else
        //                        hsDupFields.Add(li.Value.ToString(), 1);
        //                }
        //                else
        //                    hsDupFields.Add(li.Value.ToString(), 1);
        //                drT = null;

        //                string caption = setCaption(lblReportSrc.Text, li.Value.ToString(), "") + hsDupFields[li.Value.ToString()];
        //                hsFieldNames.Add(li.Value.ToString(), caption);
        //                if (caption.Trim() == "")
        //                {
        //                    DataRow[] drF = dtMasDetail.Select("attrib_id='" + li.Value.Substring(li.Value.IndexOf("].[") + 3).TrimEnd(']') + "'");
        //                    if (drF.Length > 0)
        //                        caption = drF[0]["display_att"].ToString();
        //                    drF = null;
        //                }
        //                if (li.Value.IndexOf("].[") == -1)
        //                    cols += "[" + getAttribId(lblReportSrc.Text, li.Value) + "] as [" + li.Text + "],";
        //                else
        //                {
        //                    string attrib_id = getAttribId(lblReportSrc.Text, getAttribId(lblReportSrc.Text, li.Value.Substring(li.Value.IndexOf("].[") + 3).TrimEnd(']')));

        //                    if (dtMasDetail.Select("attrib_id='" + li.Value.Substring(li.Value.IndexOf("].[") + 3).TrimEnd(']') + "'").Length > 0)
        //                    {
        //                        DataRow[] drF = dtMasDetail.Select("attrib_id='" + li.Value.Substring(li.Value.IndexOf("].[") + 3).TrimEnd(']') + "'");
        //                        string tName = hdd.GetColumnValue("select object_table from sy_obj where object_id='" + drF[0]["master_obj"].ToString() + "'");
        //                        cols += "(select top 1 " + drF[0]["display_att"].ToString() + " from " + tName + " where af_row_id=" + tabName + "." + attrib_id + ") as [" + caption + "],";
        //                    }
        //                    else if (dtBind.Select("control_attrib_id='" + attrib_id + "'").Length > 0)
        //                    {
        //                        DataRow[] drF = dtBind.Select("control_attrib_id='" + attrib_id + "'");
        //                        //(select top 1 emp_lname + '  ' + emp_fname from ap_emp as A where A.emp_id=ap_emp.report_emp_id)as report_emp_id
        //                        if (drF[0]["bind_table"].ToString().IndexOf(",") == -1)
        //                            cols += "(select top 1 " + drF[0]["bind_text"].ToString() + " from " + drF[0]["bind_table"].ToString() + " As BT1 where BT1." + drF[0]["bind_value"].ToString() + "=" + tabName + "." + attrib_id + ") as [" + caption + "],";
        //                        else//multi tables in bind_table
        //                        {
        //                            //(select top 1 customer_name from bu_customer A,bu_program B where A.customer_id = B.customer_id and A.customer_id=2)
        //                            string[] tables = drF[0]["bind_table"].ToString().Split(',');
        //                            cols += "(select top 1 " + drF[0]["bind_text"].ToString() + " from ";
        //                            string tmpStr = "";
        //                            Hashtable hsTmp = new Hashtable();
        //                            for (int i = 0; i < tables.Length; i++)
        //                            {
        //                                tmpStr += tables[i] + " As BT" + (i + 1) + ",";
        //                                hsTmp.Add(tables[i], "BT" + (i + 1));
        //                            }
        //                            cols += tmpStr.TrimEnd(',');
        //                            tmpStr = drF[0]["bind_parameter"].ToString();
        //                            if (tmpStr.Trim() != "")
        //                            {
        //                                foreach (string key in hsTmp.Keys)
        //                                    tmpStr = tmpStr.Replace(key, hsTmp[key].ToString());
        //                                cols += " where " + tmpStr + " and " + drF[0]["bind_value"].ToString() + "=" + tabName + "." + attrib_id + ") as [" + caption + "],";
        //                            }
        //                            else
        //                                cols += " where " + drF[0]["bind_value"].ToString() + "=" + tabName + "." + attrib_id + ") as [" + caption + "],";
        //                            hsTmp = null;
        //                        }
        //                    }
        //                    //createdby/modifiedby conversion
        //                    else if (attrib_id.ToLower() == "created_at" || attrib_id.ToLower() == "modified_at")
        //                    {
        //                        DataTable dtZone = new DataTable();
        //                        string tQry = "select utc_offset from sy_timezone where timezone_id = (select time_zone from sy_usr where af_row_id='" + Session["user_afrowid"].ToString() + "')";
        //                        dtZone = hdd.GetDataTable(tQry);
        //                        if (dtZone.Rows.Count > 0)
        //                        {
        //                            string offset = dtZone.Rows[0]["utc_offset"].ToString();
        //                            if (offset.IndexOf(".") != -1)
        //                            {
        //                                int mins = Convert.ToInt32(offset.Substring(offset.IndexOf(".") + 1));
        //                                int hrs = Convert.ToInt32(offset.Substring(0, offset.IndexOf(".")));
        //                                cols += "(select dateadd(minute," + mins.ToString() + ",dateadd(hour," + hrs.ToString() + "," + attrib_id + "))) as [" + caption + "],";
        //                            }
        //                            else
        //                                cols += "(select dateadd(hour," + offset + "," + attrib_id + ")) as [" + caption + "],";
        //                        }
        //                        else
        //                            cols += "[" + attrib_id + "] as [" + caption + "],";
        //                        dtZone = null;
        //                    }
        //                    //created/modified timezone conversion
        //                    else if (attrib_id.ToLower() == "created_by" || attrib_id.ToLower() == "modified_by" || attrib_id.ToLower() == "owner_id")
        //                    {
        //                        string objName = li.Value.Substring(0, li.Value.IndexOf("]")).Replace("[", "").Replace("]", "");
        //                        cols += "(" + getOwnerName(attrib_id, objName) + ") as [" + caption + "],";
        //                    }
        //                    else
        //                        cols += "[" + attrib_id + "] as [" + caption + "],";
        //                }
        //                caption = "";
        //            }
        //            sql = "select " + cols.TrimEnd(',') + " from " + tabName;
        //        }

        //        createDataTable(1, ref dsReport);
        //        dt = dsReport.Tables["p_sy_report_att"];
        //        fillSelectedValues(ref dt);
        //    }

        //    //applying security
        //    if (lblReportSrc.Text.ToLower() == "object")
        //    {
        //        if (getWhereCondition() == "")
        //            sql += " where 1=1";
        //        else
        //            sql += " where " + getWhereCondition();
        //    }
        //    xParent = xDoc.CreateElement("DataSource");
        //    xChild = xDoc.CreateElement("ConnectionString");
        //    xChild.InnerText = makeOLEDBConnectionString(Session["dbcon"].ToString());
        //    xParent.AppendChild(xChild);
        //    xNode = xDoc.CreateElement("RecordSource");
        //    xNode.InnerText = sql;
        //    xParent.AppendChild(xNode);
        //    reportNode.AppendChild(xParent);
        //    #endregion

        //    if (checkData(sql))
        //        lnkExport.Enabled = true;
        //    else
        //        lnkExport.Enabled = false;

        //    Hashtable hsDt = new Hashtable();
        //    if (lblReportSrc.Text.ToLower() == "sql")
        //        hsDt = getSqlDataTypes(sql);

        //    string currency = getCurrency(Session["user_afrowid"].ToString());

        //    #region Layout information
        //    //Calculating width
        //    hsReportWidth.Clear();
        //    int minWidth = 3500;
        //    reportWidth = 0;
        //    if (lblReportSrc.Text.ToLower() == "object")
        //    {
        //        for (int i = 0; i < dt.Rows.Count; i++)
        //        {
        //            int width = getFieldLengthForObject(dt.Rows[i]["attrib_id"].ToString(), cmbObjects.SelectedValue.Substring(cmbObjects.SelectedValue.IndexOf("@") + 1), tabName);
        //            hsReportWidth.Add(dt.Rows[i]["attrib_id"].ToString(), width);
        //            reportWidth += width;
        //        }
        //    }
        //    else
        //    {
        //        hsReportWidth = getFieldLengthForQuery(sql, cmbObjects.SelectedValue.Substring(cmbObjects.SelectedValue.IndexOf("@") + 1), hsDt);
        //        foreach (string key in hsReportWidth.Keys)
        //            reportWidth += Convert.ToInt32(hsReportWidth[key].ToString());
        //    }

        //    reportWidth += hsReportWidth.Count * 50;//space width needs to be added
        //    if (reportWidth <= minWidth)
        //        reportWidth = reportWidth + minWidth;
        //    xParent = xDoc.CreateElement("Layout");
        //    xChild = xDoc.CreateElement("Width");
        //    xChild.InnerText = (reportWidth).ToString();
        //    xParent.AppendChild(xChild);

        //    xNode = xDoc.CreateElement("Orientation");
        //    xNode.InnerText = "2";
        //    xParent.AppendChild(xNode);

        //    xNode = xDoc.CreateElement("PaperSize");
        //    xNode.InnerText = "5";
        //    xParent.AppendChild(xNode);
        //    reportNode.AppendChild(xParent);

        //    xParent = xDoc.CreateElement("Font");
        //    xChild = xDoc.CreateElement("Name");
        //    xChild.InnerText = "Arial";
        //    xParent.AppendChild(xChild);
        //    xChild = xDoc.CreateElement("Size");
        //    xChild.InnerText = "10";
        //    xParent.AppendChild(xChild);
        //    reportNode.AppendChild(xParent);

        //    xNode = xDoc.CreateElement("OnOpen");
        //    xNode.InnerText = "' -- style script start " + Convert.ToChar(13) + Convert.ToChar(10) + "_styleCtr = 0 " + Convert.ToChar(13) + Convert.ToChar(10) + "' -- style script end";
        //    reportNode.AppendChild(xNode);

        //    xNode = xDoc.CreateElement("GrowShrinkMode");
        //    xNode.InnerText = "1";
        //    reportNode.AppendChild(xNode);

        //    #endregion

        //    #region Grouping Sections

        //    xParent = xDoc.CreateElement("Groups");

        //    //xWriter.WriteStartElement("Groups");
        //    DataTable dtG = dsReport.Tables["p_report_grouping"];
        //    if (dtG == null)
        //        dtG = new DataTable();
        //    for (int i = 0; i < dtG.Rows.Count; i++)
        //    {
        //        DataRow dr = dtG.Rows[i];
        //        xChild = xDoc.CreateElement("Group");
        //        xInnerChild = xDoc.CreateElement("Name");
        //        xInnerChild.InnerText = "Group" + (i + 1).ToString();
        //        xChild.AppendChild(xInnerChild);
        //        //Group by

        //        xInnerChild = xDoc.CreateElement("GroupBy");
        //        string caption = "";

        //        ////get caption from attribute
        //        //if (dsReport.Tables.Contains("p_sy_report_att"))
        //        //{
        //        //    DataRow[] drF = dsReport.Tables["p_sy_report_att"].Select("attrib_id='" + dr["grouping_field"].ToString() + "'");
        //        //    if (drF.Length > 0)
        //        //        caption = drF[0]["caption"].ToString();
        //        //    drF = null;
        //        //}
        //        //else
        //        //    caption = setCaption(lblReportSrc.Text, dr["grouping_field"].ToString(), "");

        //        if (lblReportSrc.Text.ToLower() == "object")
        //            //caption = "[" + caption + "]";
        //            caption = "[" + hsFieldNames[dr["grouping_field"].ToString()].ToString() + "]";
        //        else if (lblReportSrc.Text.ToLower() == "sql")
        //        {
        //            if (dr["grouping_field"].ToString().IndexOf("].[") == -1)
        //                caption = dr["grouping_field"].ToString();
        //            else
        //                caption = dr["grouping_field"].ToString().Substring(dr["grouping_field"].ToString().IndexOf("].[") + 3).TrimEnd(']');
        //        }
        //        xInnerChild.InnerText = caption;
        //        xChild.AppendChild(xInnerChild);

        //        xInnerChild = xDoc.CreateElement("Sort");
        //        xInnerChild.InnerText = dr["grouping_order"].ToString().ToLower() == "ascending" ? "1" : "2";
        //        xChild.AppendChild(xInnerChild);

        //        xParent.AppendChild(xChild);
        //        dr = null;
        //    }
        //    dtG = null;

        //    reportNode.AppendChild(xParent);
        //    #endregion

        //    #region Sections
        //    xParent = xDoc.CreateElement("Sections");

        //    //Detail section
        //    xChild = xDoc.CreateElement("Section");
        //    xInnerChild = xDoc.CreateElement("Name");
        //    xInnerChild.InnerText = "Detail";
        //    xChild.AppendChild(xInnerChild);
        //    xInnerChild = xDoc.CreateElement("Type");
        //    xInnerChild.InnerText = "0";
        //    xChild.AppendChild(xInnerChild);
        //    xInnerChild = xDoc.CreateElement("Height");
        //    xInnerChild.InnerText = "300";
        //    xChild.AppendChild(xInnerChild);

        //    hsStyle = getCSSProperies(".Grid_Row1");
        //    alColor = hsStyle["BackgroundColor"].ToString();
        //    alColor = "\"" + alColor + "\"";
        //    xNode = xDoc.CreateElement("OnPrint");
        //    //xNode.InnerText = "' -- style script start " + Convert.ToChar(13) + Convert.ToChar(10) + " detail.BackColor = iif(_styleCtr mod 2 = 0, rgb(255,255,255), rgb(197,242,171)) " + Convert.ToChar(13) + Convert.ToChar(10) + "_styleCtr = _styleCtr + 1 " + Convert.ToChar(13) + Convert.ToChar(10) + "' -- style script end";//191,219 //228,240,255
        //    xNode.InnerText = "' -- style script start " + Convert.ToChar(13) + Convert.ToChar(10) + " detail.BackColor = iif(_styleCtr mod 2 = 0," + "\"#FFFFFF\"" + ", " + alColor + ")" + Convert.ToChar(13) + Convert.ToChar(10) + "_styleCtr = _styleCtr + 1 " + Convert.ToChar(13) + Convert.ToChar(10) + "' -- style script end";//191,219 //228,240,255
        //    xChild.AppendChild(xNode);
        //    xParent.AppendChild(xChild);

        //    //Header section
        //    xChild = xDoc.CreateElement("Section");
        //    xInnerChild = xDoc.CreateElement("Name");
        //    xInnerChild.InnerText = "Header";
        //    xChild.AppendChild(xInnerChild);
        //    xInnerChild = xDoc.CreateElement("Type");
        //    xInnerChild.InnerText = "1";
        //    xChild.AppendChild(xInnerChild);
        //    xInnerChild = xDoc.CreateElement("Height");
        //    if (txtHeaderText.Text.Trim() == "")
        //        xInnerChild.InnerText = "1360";
        //    else
        //        xInnerChild.InnerText = "1000";
        //    xChild.AppendChild(xInnerChild);
        //    xInnerChild = xDoc.CreateElement("Repeat");
        //    xInnerChild.InnerText = "-1";
        //    xChild.AppendChild(xInnerChild);

        //    string sTemp = HttpContext.Current.Request.Url.AbsoluteUri.Substring(0, HttpContext.Current.Request.Url.AbsoluteUri.LastIndexOf("/"));

        //    string customlogo = getLogo();
        //    if (customlogo.Trim() != "")
        //        sTemp = sTemp + "/" + customlogo;
        //    else
        //    {
        //        sTemp = sTemp + "/images/" + HttpContext.Current.Session["theme"].ToString().ToLower().Replace("theme", "");
        //        sTemp = sTemp + "/logo.gif";
        //    }

        //    xNode = xDoc.CreateElement("OnPrint");
        //    xNode.InnerText = "logoField.Picture=\"" + sTemp + "\"";
        //    xChild.AppendChild(xNode);
        //    xParent.AppendChild(xChild);

        //    //Footer
        //    xChild = xDoc.CreateElement("Section");
        //    xInnerChild = xDoc.CreateElement("Name");
        //    xInnerChild.InnerText = "Footer";
        //    xChild.AppendChild(xInnerChild);
        //    xInnerChild = xDoc.CreateElement("Type");
        //    xInnerChild.InnerText = "2";
        //    xChild.AppendChild(xInnerChild);
        //    xInnerChild = xDoc.CreateElement("Height");
        //    xInnerChild.InnerText = "300";
        //    xChild.AppendChild(xInnerChild);
        //    xParent.AppendChild(xChild);

        //    //Page Header
        //    hsStyle = getCSSProperies(".Grid_Header");
        //    xChild = xDoc.CreateElement("Section");
        //    xInnerChild = xDoc.CreateElement("Name");
        //    xInnerChild.InnerText = "PageHeader";
        //    xChild.AppendChild(xInnerChild);
        //    xInnerChild = xDoc.CreateElement("Type");
        //    xInnerChild.InnerText = "3";
        //    xChild.AppendChild(xInnerChild);
        //    xInnerChild = xDoc.CreateElement("Height");
        //    xInnerChild.InnerText = "300";
        //    xChild.AppendChild(xInnerChild);
        //    xInnerChild = xDoc.CreateElement("BackColor");
        //    xInnerChild.InnerText = hsStyle["BackgroundColor"].ToString(); //"16431752";
        //    xChild.AppendChild(xInnerChild);
        //    xInnerChild = xDoc.CreateElement("Repeat");
        //    xInnerChild.InnerText = "-1";
        //    xChild.AppendChild(xInnerChild);
        //    xParent.AppendChild(xChild);
        //    hsStyle = null;
        //    //PageFooter
        //    xChild = xDoc.CreateElement("Section");
        //    xInnerChild = xDoc.CreateElement("Name");
        //    xInnerChild.InnerText = "PageFooter";
        //    xChild.AppendChild(xInnerChild);
        //    xInnerChild = xDoc.CreateElement("Type");
        //    xInnerChild.InnerText = "4";
        //    xChild.AppendChild(xInnerChild);
        //    xInnerChild = xDoc.CreateElement("Height");
        //    xInnerChild.InnerText = "300";
        //    xChild.AppendChild(xInnerChild);
        //    xParent.AppendChild(xChild);

        //    //Grouping Header/Footer Sections
        //    DataTable dtS = dsReport.Tables["p_report_grouping"];
        //    int sec = 5;
        //    if (dtS == null)
        //        dtS = new DataTable();
        //    for (int k = 0; k < dtS.Rows.Count; k++)
        //    {
        //        DataRow dr = dt.Rows[k];
        //        //Group Header 
        //        xChild = xDoc.CreateElement("Section");
        //        xInnerChild = xDoc.CreateElement("Name");
        //        xInnerChild.InnerText = "Group" + (k + 1).ToString() + "_Header";
        //        xChild.AppendChild(xInnerChild);
        //        xInnerChild = xDoc.CreateElement("Type");
        //        xInnerChild.InnerText = sec.ToString();
        //        xChild.AppendChild(xInnerChild);
        //        xInnerChild = xDoc.CreateElement("Height");
        //        xInnerChild.InnerText = "300";
        //        xChild.AppendChild(xInnerChild);
        //        xParent.AppendChild(xChild);

        //        sec++;

        //        //Group Footer
        //        xChild = xDoc.CreateElement("Section");
        //        xInnerChild = xDoc.CreateElement("Name");
        //        xInnerChild.InnerText = "Group" + (k + 1).ToString() + "_Footer";
        //        xChild.AppendChild(xInnerChild);
        //        xInnerChild = xDoc.CreateElement("Type");
        //        xInnerChild.InnerText = sec.ToString();
        //        xChild.AppendChild(xInnerChild);
        //        xInnerChild = xDoc.CreateElement("Height");
        //        xInnerChild.InnerText = "300";
        //        xChild.AppendChild(xInnerChild);
        //        xParent.AppendChild(xChild);
        //        sec++;
        //    }
        //    reportNode.AppendChild(xParent);
        //    #endregion

        //    #region Report Title
        //    xParent = xDoc.CreateElement("Fields");
        //    //Detail section
        //    xChild = xDoc.CreateElement("Field");
        //    xInnerChild = xDoc.CreateElement("Name");
        //    xInnerChild.InnerText = "title";
        //    xChild.AppendChild(xInnerChild);

        //    xInnerChild = xDoc.CreateElement("Section");
        //    xInnerChild.InnerText = "1";
        //    xChild.AppendChild(xInnerChild);

        //    string tmp = txtRepTitle.Text.Trim() == "" ? cmbObjects.SelectedItem.Text : txtRepTitle.Text; //"Untitled Report"
        //    if (tmp == cmbObjects.SelectedItem.Text) //"Untitled Report")
        //    {
        //        if (txtRepName.Text.Trim() != "")
        //            tmp = txtRepName.Text;
        //    }
        //    xInnerChild = xDoc.CreateElement("Text");
        //    xInnerChild.InnerText = tmp;
        //    xChild.AppendChild(xInnerChild);

        //    xInnerChild = xDoc.CreateElement("Height");
        //    xInnerChild.InnerText = "400";
        //    xChild.AppendChild(xInnerChild);

        //    xInnerChild = xDoc.CreateElement("Left");
        //    if (chkDisplayLogo.Checked)
        //        xInnerChild.InnerText = ((((reportWidth / 2) - (getLength(tmp) / 2)) + 1500).ToString());
        //    else
        //        xInnerChild.InnerText = ((reportWidth / 2) - (getLength(tmp) / 2)).ToString();
        //    xChild.AppendChild(xInnerChild);

        //    xInnerChild = xDoc.CreateElement("Width");
        //    xInnerChild.InnerText = getLength(tmp).ToString();
        //    xChild.AppendChild(xInnerChild);

        //    xInnerChild = xDoc.CreateElement("Top");
        //    xInnerChild.InnerText = "300";
        //    xChild.AppendChild(xInnerChild);

        //    xInnerChild = xDoc.CreateElement("Align");
        //    xInnerChild.InnerText = "6";
        //    xChild.AppendChild(xInnerChild);

        //    xInnerChild = xDoc.CreateElement("WordWrap");
        //    xInnerChild.InnerText = "0";
        //    xChild.AppendChild(xInnerChild);

        //    hsStyle = getCSSProperies(".pgForm_title");
        //    xInnerChild = xDoc.CreateElement("ForeColor");
        //    xInnerChild.InnerText = hsStyle["Color"].ToString(); // "16711680";
        //    xChild.AppendChild(xInnerChild);
        //    //Font
        //    xInnerChild = xDoc.CreateElement("Font");
        //    xNode = xDoc.CreateElement("Bold");
        //    xNode.InnerText = "-1";
        //    xInnerChild.AppendChild(xNode);
        //    xNode = xDoc.CreateElement("Name");
        //    xNode.InnerText = "Arial";
        //    xInnerChild.AppendChild(xNode);
        //    xNode = xDoc.CreateElement("Size");
        //    xNode.InnerText = hsStyle["FontSize"].ToString();
        //    xInnerChild.AppendChild(xNode);

        //    xChild.AppendChild(xInnerChild);
        //    xParent.AppendChild(xChild);
        //    hsStyle = null;
        //    #endregion

        //    #region Report Labels/Captions
        //    int left = 50;
        //    int idx = 1;
        //    hsStyle = getCSSProperies(".Grid_Report_Header");
        //    Hashtable hsCaption = new Hashtable();
        //    foreach (DataRow dr in dt.Rows)
        //    {
        //        xChild = xDoc.CreateElement("Field");

        //        xInnerChild = xDoc.CreateElement("Name");
        //        xInnerChild.InnerText = "lbl" + idx.ToString();
        //        xChild.AppendChild(xInnerChild);

        //        xInnerChild = xDoc.CreateElement("Section");
        //        xInnerChild.InnerText = "3";
        //        xChild.AppendChild(xInnerChild);

        //        xInnerChild = xDoc.CreateElement("Text");
        //        string caption = setCaption(lblReportSrc.Text, dr["attrib_id"].ToString(), dr["caption"].ToString());
        //        hsCaption.Add(dr["attrib_id"].ToString(), dr["caption"].ToString());
        //        xInnerChild.InnerText = caption;
        //        caption = "";
        //        xChild.AppendChild(xInnerChild);

        //        xInnerChild = xDoc.CreateElement("Left");
        //        xInnerChild.InnerText = left.ToString();
        //        xChild.AppendChild(xInnerChild);
        //        xInnerChild = xDoc.CreateElement("Width");
        //        if (lblReportSrc.Text.ToLower() == "sql")
        //        {
        //            if (dr["attrib_id"].ToString().IndexOf("].[") == -1)
        //                xInnerChild.InnerText = hsReportWidth[dr["attrib_id"].ToString()].ToString();
        //            else
        //                xInnerChild.InnerText = hsReportWidth[dr["attrib_id"].ToString().Substring(dr["attrib_id"].ToString().IndexOf("].[") + 3).TrimEnd(']')].ToString();
        //        }
        //        else
        //            xInnerChild.InnerText = hsReportWidth[dr["attrib_id"].ToString()].ToString();

        //        xChild.AppendChild(xInnerChild);
        //        xInnerChild = xDoc.CreateElement("CanGrow");
        //        xInnerChild.InnerText = "-1";
        //        xChild.AppendChild(xInnerChild);
        //        xInnerChild = xDoc.CreateElement("Height");
        //        xInnerChild.InnerText = "300";
        //        xChild.AppendChild(xInnerChild);
        //        xInnerChild = xDoc.CreateElement("ForeColor");
        //        xInnerChild.InnerText = hsStyle["Color"].ToString();// "16777215";
        //        xChild.AppendChild(xInnerChild);

        //        xInnerChild = xDoc.CreateElement("Align");
        //        if (lblReportSrc.Text.ToLower() == "object")
        //            xInnerChild.InnerText = getAttribAlignment(lblReportSrc.Text, dr["attrib_id"].ToString());
        //        else if (lblReportSrc.Text.ToLower() == "sql")
        //            xInnerChild.InnerText = getSqlAlignment(dr["attrib_id"].ToString(), hsDt);

        //        xChild.AppendChild(xInnerChild);
        //        //Wordwrap
        //        xInnerChild = xDoc.CreateElement("WordWrap");

        //        if (dr["is_wrap"].ToString().ToLower() == "yes" || dr["is_wrap"].ToString().ToLower() == "no")
        //            xInnerChild.InnerText = dr["is_wrap"].ToString() == "Yes" ? "true" : "No";
        //        else
        //        {
        //            if (Convert.ToBoolean(dr["is_wrap"].ToString()) == true)
        //                xInnerChild.InnerText = "true";
        //            else
        //                xInnerChild.InnerText = "false";
        //        }
        //        xChild.AppendChild(xInnerChild);

        //        //Font
        //        xInnerChild = xDoc.CreateElement("Font");
        //        xNode = xDoc.CreateElement("Bold");
        //        xNode.InnerText = "true";
        //        //if (dr["is_bold"].ToString().ToLower() == "yes" || dr["is_bold"].ToString().ToLower() == "no")
        //        //    xNode.InnerText = (dr["is_bold"].ToString() == "Yes" ? "true" : "No");
        //        //else
        //        //{
        //        //    if (Convert.ToBoolean(dr["is_bold"].ToString()) == true)
        //        //        xNode.InnerText = "true";
        //        //    else
        //        //        xNode.InnerText = "false";
        //        //}
        //        xInnerChild.AppendChild(xNode);

        //        xNode = xDoc.CreateElement("Name");
        //        xNode.InnerText = "Arial";
        //        xInnerChild.AppendChild(xNode);

        //        xNode = xDoc.CreateElement("Size");
        //        xNode.InnerText = hsStyle["FontSize"].ToString();
        //        xInnerChild.AppendChild(xNode);

        //        xChild.AppendChild(xInnerChild);
        //        xParent.AppendChild(xChild);

        //        if (lblReportSrc.Text.ToLower() == "sql")
        //        {
        //            if (dr["attrib_id"].ToString().IndexOf("].[") == -1)
        //                left += (Convert.ToInt32(hsReportWidth[dr["attrib_id"].ToString()].ToString()) + 50);
        //            else
        //                left += (Convert.ToInt32(hsReportWidth[dr["attrib_id"].ToString().Substring(dr["attrib_id"].ToString().IndexOf("].[") + 3).TrimEnd(']')].ToString()) + 50);
        //        }
        //        else
        //            left += (Convert.ToInt32(hsReportWidth[dr["attrib_id"].ToString()].ToString()) + 50);
        //        idx++;
        //    }
        //    #endregion

        //    #region Report Fields/Values
        //    left = 50;
        //    idx = 1;
        //    Hashtable hsRptLocations = new Hashtable();
        //    //hsDupFields.Clear();
        //    foreach (DataRow dr in dt.Rows)
        //    {
        //        xChild = xDoc.CreateElement("Field");

        //        xInnerChild = xDoc.CreateElement("Name");
        //        xInnerChild.InnerText = "Field" + idx.ToString();
        //        xChild.AppendChild(xInnerChild);

        //        xInnerChild = xDoc.CreateElement("Section");
        //        xInnerChild.InnerText = "0";
        //        xChild.AppendChild(xInnerChild);

        //        xInnerChild = xDoc.CreateElement("Text");

        //        string caption = "";
        //        if (lblReportSrc.Text.ToLower() == "object")
        //        {
        //            caption = "[" + hsFieldNames[dr["attrib_id"].ToString()].ToString() + "]";
        //            //caption = "[" + setCaption(lblReportSrc.Text, dr["attrib_id"].ToString(), dr["caption"].ToString()) + hsDupFields[dr["caption"].ToString()].ToString() + "]";
        //        }
        //        else if (lblReportSrc.Text.ToLower() == "sql")
        //        {
        //            if (dr["attrib_id"].ToString().IndexOf("].[") == -1)
        //                caption = dr["attrib_id"].ToString();
        //            else
        //                caption = dr["attrib_id"].ToString().Substring(dr["attrib_id"].ToString().IndexOf("].[") + 3).TrimEnd(']');
        //        }
        //        xInnerChild.InnerText = caption;
        //        xChild.AppendChild(xInnerChild);

        //        string formatSyntax = "";
        //        if (lblReportSrc.Text.ToLower() == "object")
        //        {
        //            string dType = getDataType(dr["attrib_id"].ToString());
        //            if (dType == "DA")
        //                formatSyntax = sDateFormatString;
        //            else if (dType == "DT")
        //                formatSyntax = sDateTimeFormatString;
        //            else if (dType == "CU")
        //                formatSyntax = "#,##0.00";
        //        }
        //        else if (lblReportSrc.Text.ToLower() == "sql")
        //        {
        //            string dType = getSqlDataType(dr["attrib_id"].ToString(), hsDt);
        //            switch (dType.ToLower())
        //            {
        //                case "date":
        //                    formatSyntax = sDateFormatString;
        //                    break;
        //                case "datetime":
        //                    formatSyntax = sDateTimeFormatString;
        //                    break;
        //                case "decimal":
        //                case "double":
        //                    formatSyntax = "#,##0.00";
        //                    break;
        //            }
        //        }
        //        xInnerChild = xDoc.CreateElement("Format");
        //        xInnerChild.InnerText = formatSyntax;
        //        xChild.AppendChild(xInnerChild);

        //        xInnerChild = xDoc.CreateElement("Left");
        //        xInnerChild.InnerText = left.ToString();
        //        xChild.AppendChild(xInnerChild);
        //        hsRptLocations.Add(dr["attrib_id"], left);
        //        xInnerChild = xDoc.CreateElement("Calculated");
        //        xInnerChild.InnerText = "true";
        //        xChild.AppendChild(xInnerChild);
        //        xInnerChild = xDoc.CreateElement("Width");
        //        //xInnerChild.InnerText = "1000";
        //        //xInnerChild.InnerText = hsReportWidth[dr["attrib_id"].ToString()].ToString();
        //        if (lblReportSrc.Text.ToLower() == "sql")
        //        {
        //            if (dr["attrib_id"].ToString().IndexOf("].[") == -1)
        //                xInnerChild.InnerText = hsReportWidth[dr["attrib_id"].ToString()].ToString();
        //            else
        //                xInnerChild.InnerText = hsReportWidth[dr["attrib_id"].ToString().Substring(dr["attrib_id"].ToString().IndexOf("].[") + 3).TrimEnd(']')].ToString();
        //        }
        //        else
        //            xInnerChild.InnerText = hsReportWidth[dr["attrib_id"].ToString()].ToString();

        //        xChild.AppendChild(xInnerChild);
        //        xInnerChild = xDoc.CreateElement("Align");
        //        if (lblReportSrc.Text.ToLower() == "object")
        //            xInnerChild.InnerText = getAttribAlignment(lblReportSrc.Text, dr["attrib_id"].ToString());
        //        else if (lblReportSrc.Text.ToLower() == "sql")
        //            xInnerChild.InnerText = getSqlAlignment(dr["attrib_id"].ToString(), hsDt);
        //        xChild.AppendChild(xInnerChild);

        //        //Wordwrap
        //        xInnerChild = xDoc.CreateElement("WordWrap");
        //        if (dr["is_wrap"].ToString().ToLower() == "yes" || dr["is_wrap"].ToString().ToLower() == "no")
        //            xInnerChild.InnerText = dr["is_wrap"].ToString() == "Yes" ? "true" : "No";
        //        else
        //        {
        //            if (Convert.ToBoolean(dr["is_wrap"].ToString()) == true)
        //                xInnerChild.InnerText = "true";
        //            else
        //                xInnerChild.InnerText = "false";
        //        }
        //        xChild.AppendChild(xInnerChild);

        //        xInnerChild = xDoc.CreateElement("CanGrow");
        //        xInnerChild.InnerText = "-1";
        //        xChild.AppendChild(xInnerChild);

        //        xInnerChild = xDoc.CreateElement("Height");
        //        xInnerChild.InnerText = "300";
        //        xChild.AppendChild(xInnerChild);

        //        xInnerChild = xDoc.CreateElement("Font");
        //        //Bold
        //        xNode = xDoc.CreateElement("Bold");
        //        if (dr["is_bold"].ToString().ToLower() == "yes" || dr["is_bold"].ToString().ToLower() == "no")
        //            xNode.InnerText = dr["is_bold"].ToString() == "Yes" ? "true" : "No";
        //        else
        //        {
        //            if (Convert.ToBoolean(dr["is_bold"].ToString()) == true)
        //                xNode.InnerText = "true";
        //            else
        //                xNode.InnerText = "false";
        //        }
        //        xInnerChild.AppendChild(xNode);

        //        xNode = xDoc.CreateElement("Name");
        //        xNode.InnerText = "Arial";
        //        xInnerChild.AppendChild(xNode);

        //        xNode = xDoc.CreateElement("Size");
        //        xNode.InnerText = "8";
        //        xInnerChild.AppendChild(xNode);

        //        xChild.AppendChild(xInnerChild);

        //        xParent.AppendChild(xChild);

        //        //left += (Convert.ToInt32(hsReportWidth[dr["attrib_id"].ToString()].ToString())+50);
        //        if (lblReportSrc.Text.ToLower() == "sql")
        //        {
        //            if (dr["attrib_id"].ToString().IndexOf("].[") == -1)
        //                left += (Convert.ToInt32(hsReportWidth[dr["attrib_id"].ToString()].ToString()) + 50);
        //            else
        //                left += (Convert.ToInt32(hsReportWidth[dr["attrib_id"].ToString().Substring(dr["attrib_id"].ToString().IndexOf("].[") + 3).TrimEnd(']')].ToString()) + 50);
        //        }
        //        else
        //            left += (Convert.ToInt32(hsReportWidth[dr["attrib_id"].ToString()].ToString()) + 50);
        //        idx++;
        //    }
        //    dt = null;
        //    #endregion

        //    #region Logo/Picture display

        //    if (chkDisplayLogo.Checked)
        //    {
        //        xChild = xDoc.CreateElement("Field");

        //        xInnerChild = xDoc.CreateElement("Name");
        //        xInnerChild.InnerText = "logoField";
        //        xChild.AppendChild(xInnerChild);

        //        xInnerChild = xDoc.CreateElement("Section");
        //        xInnerChild.InnerText = "1";
        //        xChild.AppendChild(xInnerChild);

        //        xInnerChild = xDoc.CreateElement("Left");
        //        xInnerChild.InnerText = "10";
        //        xChild.AppendChild(xInnerChild);

        //        xInnerChild = xDoc.CreateElement("Width");
        //        xInnerChild.InnerText = "3000";
        //        xChild.AppendChild(xInnerChild);

        //        xInnerChild = xDoc.CreateElement("Top");
        //        xInnerChild.InnerText = "0";
        //        xChild.AppendChild(xInnerChild);

        //        xInnerChild = xDoc.CreateElement("Height");
        //        xInnerChild.InnerText = "1000";
        //        xChild.AppendChild(xInnerChild);

        //        xInnerChild = xDoc.CreateElement("PictureAlign");
        //        xInnerChild.InnerText = "7";
        //        xChild.AppendChild(xInnerChild);

        //        //xInnerChild = xDoc.CreateElement("PictureScale");
        //        //xInnerChild.InnerText = "1";
        //        //xChild.AppendChild(xInnerChild);

        //        xParent.AppendChild(xChild);
        //    }
        //    #endregion

        //    #region Report Grouping Header
        //    left = 50;
        //    //Header
        //    dtG = dsReport.Tables["p_report_grouping"];
        //    if (dtG != null)
        //    {
        //        if (dtG.Rows.Count > 0)
        //        {
        //            dtG = dsReport.Tables["p_report_grouping_header"];
        //            if (dtG == null)
        //                dtG = new DataTable();
        //            foreach (DataRow dr in dtG.Rows)
        //            {
        //                //Header Label
        //                xChild = xDoc.CreateElement("Field");

        //                xInnerChild = xDoc.CreateElement("Name");
        //                xInnerChild.InnerText = "Field" + idx.ToString();
        //                xChild.AppendChild(xInnerChild);

        //                xInnerChild = xDoc.CreateElement("Section");
        //                if (dr["group_sequence"].ToString() == "1")
        //                    xInnerChild.InnerText = "5";
        //                else if (dr["group_sequence"].ToString() == "2")
        //                    xInnerChild.InnerText = "7";
        //                else if (dr["group_sequence"].ToString() == "3")
        //                    xInnerChild.InnerText = "9";
        //                xChild.AppendChild(xInnerChild);
        //                xInnerChild = xDoc.CreateElement("Text");
        //                string caption = "";

        //                if (hsCaption.Contains(dr["header_field"].ToString()))
        //                    caption = hsCaption[dr["header_field"].ToString()].ToString();
        //                else
        //                {
        //                    if (lblReportSrc.Text.ToLower() == "object")
        //                        caption = setCaption(lblReportSrc.Text, dr["header_field"].ToString(), "");
        //                    else if (lblReportSrc.Text.ToLower() == "sql")
        //                    {
        //                        if (dr["header_field"].ToString().IndexOf("].[") == -1)
        //                            caption = dr["header_field"].ToString();
        //                        else
        //                            caption = dr["header_field"].ToString().Substring(dr["header_field"].ToString().IndexOf("].[") + 3).TrimEnd(']');
        //                    }
        //                }
        //                xInnerChild.InnerText = caption;
        //                //caption = "";
        //                xChild.AppendChild(xInnerChild);

        //                xInnerChild = xDoc.CreateElement("Left");
        //                xInnerChild.InnerText = left.ToString();
        //                xChild.AppendChild(xInnerChild);
        //                xInnerChild = xDoc.CreateElement("Calculated");
        //                xInnerChild.InnerText = "false";
        //                xChild.AppendChild(xInnerChild);
        //                xInnerChild = xDoc.CreateElement("Width");

        //                if (lblReportSrc.Text.ToLower() == "sql")
        //                {
        //                    if (dr["header_field"].ToString().IndexOf("].[") == -1)
        //                        xInnerChild.InnerText = hsReportWidth[dr["header_field"].ToString()].ToString();
        //                    else
        //                        xInnerChild.InnerText = hsReportWidth[dr["header_field"].ToString().Substring(dr["header_field"].ToString().IndexOf("].[") + 3).TrimEnd(']')].ToString();
        //                }
        //                else
        //                    xInnerChild.InnerText = hsReportWidth[dr["header_field"].ToString()].ToString();

        //                //xInnerChild.InnerText = hsReportWidth[dr["header_field"].ToString()].ToString();
        //                xChild.AppendChild(xInnerChild);
        //                xInnerChild = xDoc.CreateElement("Height");
        //                xInnerChild.InnerText = "300";
        //                xChild.AppendChild(xInnerChild);
        //                xInnerChild = xDoc.CreateElement("Align");
        //                xInnerChild.InnerText = "6";
        //                xChild.AppendChild(xInnerChild);

        //                //Font
        //                xInnerChild = xDoc.CreateElement("Font");
        //                xNode = xDoc.CreateElement("Bold");
        //                xNode.InnerText = "true";
        //                xInnerChild.AppendChild(xNode);
        //                xNode = xDoc.CreateElement("Name");
        //                xNode.InnerText = "Arial";
        //                xInnerChild.AppendChild(xNode);
        //                xNode = xDoc.CreateElement("Size");
        //                xNode.InnerText = "8";
        //                xInnerChild.AppendChild(xNode);
        //                xNode = xDoc.CreateElement("WordWrap");
        //                xNode.InnerText = "false";
        //                xInnerChild.AppendChild(xNode);
        //                xChild.AppendChild(xInnerChild);
        //                xParent.AppendChild(xChild);
        //                left += 1200;
        //                idx++;

        //                //Header Field
        //                xChild = xDoc.CreateElement("Field");
        //                xInnerChild = xDoc.CreateElement("Name");
        //                xInnerChild.InnerText = "Field" + idx.ToString();
        //                xChild.AppendChild(xInnerChild);
        //                xInnerChild = xDoc.CreateElement("Section");
        //                if (dr["group_sequence"].ToString() == "1")
        //                    xInnerChild.InnerText = "5";
        //                else if (dr["group_sequence"].ToString() == "2")
        //                    xInnerChild.InnerText = "7";
        //                else if (dr["group_sequence"].ToString() == "3")
        //                    xInnerChild.InnerText = "9";
        //                xChild.AppendChild(xInnerChild);

        //                xInnerChild = xDoc.CreateElement("Text");
        //                //caption = "";
        //                //if (lblReportSrc.Text.ToLower() == "object")
        //                //    caption = "[" + setCaption(lblReportSrc.Text, dr["header_field"].ToString(), "") + "]";
        //                //else if (lblReportSrc.Text.ToLower() == "sql")
        //                //{
        //                //    if (dr["header_field"].ToString().IndexOf("].[") == -1)
        //                //        caption = dr["header_field"].ToString();
        //                //    else
        //                //        caption = dr["header_field"].ToString().Substring(dr["header_field"].ToString().IndexOf("].[") + 3).TrimEnd(']');
        //                //}
        //                if (lblReportSrc.Text.ToLower() == "object")
        //                    xInnerChild.InnerText = "[" + hsFieldNames[dr["header_field"].ToString()].ToString() + "]"; //caption
        //                else
        //                {
        //                    if (dr["header_field"].ToString().IndexOf("].[") == -1)
        //                        caption = dr["header_field"].ToString();
        //                    else
        //                        caption = dr["header_field"].ToString().Substring(dr["header_field"].ToString().IndexOf("].[") + 3).TrimEnd(']');
        //                    xInnerChild.InnerText = "[" + caption + "]";
        //                }
        //                caption = "";
        //                xChild.AppendChild(xInnerChild);

        //                xInnerChild = xDoc.CreateElement("Left");
        //                xInnerChild.InnerText = left.ToString();
        //                xChild.AppendChild(xInnerChild);
        //                xInnerChild = xDoc.CreateElement("Calculated");
        //                xInnerChild.InnerText = "true";
        //                xChild.AppendChild(xInnerChild);
        //                xInnerChild = xDoc.CreateElement("Width");
        //                //xInnerChild.InnerText = hsReportWidth[dr["header_field"].ToString()].ToString(); //"1000";
        //                if (lblReportSrc.Text.ToLower() == "sql")
        //                {
        //                    if (dr["header_field"].ToString().IndexOf("].[") == -1)
        //                        xInnerChild.InnerText = hsReportWidth[dr["header_field"].ToString()].ToString();
        //                    else
        //                        xInnerChild.InnerText = hsReportWidth[dr["header_field"].ToString().Substring(dr["header_field"].ToString().IndexOf("].[") + 3).TrimEnd(']')].ToString();
        //                }
        //                else
        //                    xInnerChild.InnerText = hsReportWidth[dr["header_field"].ToString()].ToString();
        //                xChild.AppendChild(xInnerChild);
        //                xInnerChild = xDoc.CreateElement("Height");
        //                xInnerChild.InnerText = "300";
        //                xChild.AppendChild(xInnerChild);
        //                xInnerChild = xDoc.CreateElement("Align");
        //                xInnerChild.InnerText = "6";
        //                xChild.AppendChild(xInnerChild);

        //                //Font
        //                xInnerChild = xDoc.CreateElement("Font");
        //                xNode = xDoc.CreateElement("Bold");
        //                xNode.InnerText = "true";
        //                xInnerChild.AppendChild(xNode);
        //                xNode = xDoc.CreateElement("Name");
        //                xNode.InnerText = "Arial";
        //                xInnerChild.AppendChild(xNode);
        //                xNode = xDoc.CreateElement("Size");
        //                xNode.InnerText = "8";
        //                xInnerChild.AppendChild(xNode);
        //                xChild.AppendChild(xInnerChild);
        //                xParent.AppendChild(xChild);

        //                if (lblReportSrc.Text.ToLower() == "sql")
        //                {
        //                    if (dr["header_field"].ToString().IndexOf("].[") == -1)
        //                        left += (Convert.ToInt32(hsReportWidth[dr["header_field"].ToString()].ToString()));
        //                    else
        //                        left += (Convert.ToInt32(hsReportWidth[dr["header_field"].ToString().Substring(dr["header_field"].ToString().IndexOf("].[") + 3).TrimEnd(']')].ToString()));
        //                }
        //                else
        //                    left += (Convert.ToInt32(hsReportWidth[dr["header_field"].ToString()].ToString()));
        //                //left += Convert.ToInt32(hsReportWidth[dr["header_field"].ToString()].ToString());// 1200;
        //                idx++;
        //            }
        //        }
        //    }
        //    dtG = null;
        //    #endregion

        //    #region Report Grouping Subtotal
        //    left = 50;
        //    //Header
        //    dtS = dsReport.Tables["p_report_grouping"];
        //    if (dtS != null)
        //    {
        //        if (dtS.Rows.Count > 0)
        //        {
        //            dtS = dsReport.Tables["p_report_grouping_subtotal"];
        //            if (dtS == null)
        //                dtS = new DataTable();
        //            foreach (DataRow dr in dtS.Rows)
        //            {
        //                //Header Label
        //                xChild = xDoc.CreateElement("Field");
        //                xInnerChild = xDoc.CreateElement("Name");
        //                xInnerChild.InnerText = "Field" + idx.ToString();
        //                xChild.AppendChild(xInnerChild);
        //                xInnerChild = xDoc.CreateElement("Section");
        //                if (dr["group_sequence"].ToString() == "1")
        //                    xInnerChild.InnerText = "6";
        //                else if (dr["group_sequence"].ToString() == "2")
        //                    xInnerChild.InnerText = "8";
        //                else if (dr["group_sequence"].ToString() == "3")
        //                    xInnerChild.InnerText = "10";
        //                xChild.AppendChild(xInnerChild);

        //                xInnerChild = xDoc.CreateElement("Text");
        //                string formula = "";
        //                string caption = "";

        //                if (hsCaption.Contains(dr["subtotal_field"].ToString()))
        //                    caption = hsCaption[dr["subtotal_field"].ToString()].ToString();
        //                else
        //                    caption = setCaption(lblReportSrc.Text, dr["subtotal_field"].ToString(), "");

        //                string dtype = getDataType(dr["subtotal_field"].ToString());
        //                if (lblReportSrc.Text.ToLower() == "object")
        //                {
        //                    if (dtype == "CU")
        //                        formula = "\"" + currency + " \"+" + " Sum([" + hsFieldNames[dr["subtotal_field"].ToString()].ToString() + "])";//caption setCaption(lblReportSrc.Text, dr["subtotal_field"].ToString(), "")
        //                    else if (dtype == "DC")
        //                        formula = "Format(Sum([" + hsFieldNames[dr["subtotal_field"].ToString()].ToString() + "])," + "\"0.00\")";//caption
        //                    else
        //                        formula = "Sum([" + hsFieldNames[dr["subtotal_field"].ToString()].ToString() + "])";//caption;//#,##0.00
        //                }
        //                else if (lblReportSrc.Text.ToLower() == "sql")
        //                {
        //                    dtype = getSqlDataType(dr["subtotal_field"].ToString(), hsDt);
        //                    //if (dr["subtotal_field"].ToString().IndexOf("].[") == -1)
        //                    //    formula = "Format(Sum(" + caption + ")," + "\"0.00\")";//dr["subtotal_field"].ToString()
        //                    //else
        //                    if (dr["subtotal_field"].ToString().IndexOf("].[") == -1)
        //                        caption = dr["subtotal_field"].ToString();
        //                    else
        //                        caption = dr["subtotal_field"].ToString().Substring(dr["subtotal_field"].ToString().IndexOf("].[") + 3).TrimEnd(']');
        //                    //xInnerChild.InnerText = "[" + caption + "]";

        //                    if (dtype.ToLower() == "double")
        //                        formula = "\"" + currency + " \"+" + " Sum([" + caption + "])";//caption setCaption(lblReportSrc.Text, dr["subtotal_field"].ToString(), "")
        //                    else if (dtype.ToLower() == "decimal")
        //                        formula = "Format(Sum([" + caption + "])," + "\"0.00\")";//caption
        //                    else
        //                        formula = "Sum([" + caption + "])";//caption
        //                    //formula = "Format(Sum(" + caption + ")," + "\"0.00\")"; //dr["subtotal_field"].ToString().Substring(dr["subtotal_field"].ToString().IndexOf("].[") + 3).TrimEnd(']')
        //                }
        //                xInnerChild.InnerText = formula;
        //                formula = "";

        //                xChild.AppendChild(xInnerChild);
        //                xInnerChild = xDoc.CreateElement("Left");
        //                xInnerChild.InnerText = hsRptLocations[dr["subtotal_field"].ToString()].ToString();
        //                xChild.AppendChild(xInnerChild);
        //                xInnerChild = xDoc.CreateElement("Calculated");
        //                xInnerChild.InnerText = "true";
        //                xChild.AppendChild(xInnerChild);
        //                xInnerChild = xDoc.CreateElement("Width");
        //                if (lblReportSrc.Text.ToLower() == "sql")
        //                {
        //                    if (dr["subtotal_field"].ToString().IndexOf("].[") == -1)
        //                        xInnerChild.InnerText = hsReportWidth[dr["subtotal_field"].ToString()].ToString();
        //                    else
        //                        xInnerChild.InnerText = hsReportWidth[dr["subtotal_field"].ToString().Substring(dr["subtotal_field"].ToString().IndexOf("].[") + 3).TrimEnd(']')].ToString();
        //                }
        //                else
        //                    xInnerChild.InnerText = hsReportWidth[dr["subtotal_field"].ToString()].ToString();
        //                //xInnerChild.InnerText = hsReportWidth[dr["subtotal_field"].ToString()].ToString(); //"1000";
        //                xChild.AppendChild(xInnerChild);
        //                xInnerChild = xDoc.CreateElement("Height");
        //                xInnerChild.InnerText = "300";
        //                xChild.AppendChild(xInnerChild);
        //                xInnerChild = xDoc.CreateElement("Align");
        //                xInnerChild.InnerText = "8";
        //                xChild.AppendChild(xInnerChild);

        //                //Font
        //                xInnerChild = xDoc.CreateElement("Font");
        //                xNode = xDoc.CreateElement("Bold");
        //                xNode.InnerText = "true";
        //                xInnerChild.AppendChild(xNode);
        //                xNode = xDoc.CreateElement("Name");
        //                xNode.InnerText = "Arial";
        //                xInnerChild.AppendChild(xNode);
        //                xNode = xDoc.CreateElement("Size");
        //                xNode.InnerText = "8";
        //                xInnerChild.AppendChild(xNode);
        //                xChild.AppendChild(xInnerChild);
        //                xParent.AppendChild(xChild);

        //                idx++;
        //            }
        //        }
        //    }
        //    dtS = null;
        //    #endregion

        //    #region Report Grand Total
        //    left = 50;
        //    //Header
        //    dtG = dsReport.Tables["p_report_grouping"];
        //    if (dtG != null)
        //    {
        //        if (dtG.Rows.Count > 0)
        //        {
        //            dtG = dsReport.Tables["p_report_grouping_grand_total"];
        //            if (dtG == null)
        //                dtG = new DataTable();
        //            foreach (DataRow dr in dtG.Rows)
        //            {
        //                //Header Label
        //                xChild = xDoc.CreateElement("Field");
        //                xInnerChild = xDoc.CreateElement("Name");
        //                xInnerChild.InnerText = "Field" + idx.ToString();
        //                xChild.AppendChild(xInnerChild);
        //                xInnerChild = xDoc.CreateElement("Section");
        //                xInnerChild.InnerText = "2";
        //                xChild.AppendChild(xInnerChild);
        //                xInnerChild = xDoc.CreateElement("Text");
        //                string formula = "", caption = "";
        //                string dtype = getDataType(dr["grand_total_field"].ToString());

        //                if (hsCaption.Contains(dr["grand_total_field"].ToString()))
        //                    caption = hsCaption[dr["grand_total_field"].ToString()].ToString();
        //                else
        //                    caption = setCaption(lblReportSrc.Text, dr["grand_total_field"].ToString(), "");

        //                if (lblReportSrc.Text.ToLower() == "object")
        //                {
        //                    if (dtype == "CU")
        //                        formula = "\"" + currency + " \" +" + "Sum([" + hsFieldNames[dr["grand_total_field"].ToString()].ToString() + "])";//caption
        //                    else if (dtype == "DC")
        //                        formula = "Format(Sum([" + hsFieldNames[dr["grand_total_field"].ToString()].ToString() + "])," + "\"0.00\")"; //caption setCaption(lblReportSrc.Text, dr["grand_total_field"].ToString(), "")
        //                    else
        //                        formula = "Sum([" + hsFieldNames[dr["grand_total_field"].ToString()].ToString() + "])";//caption setCaption(lblReportSrc.Text, dr["grand_total_field"].ToString(), "")
        //                }
        //                else if (lblReportSrc.Text.ToLower() == "sql")
        //                {
        //                    dtype = getSqlDataType(dr["grand_total_field"].ToString(), hsDt);
        //                    if (dr["grand_total_field"].ToString().IndexOf("].[") == -1)
        //                        caption = dr["grand_total_field"].ToString();
        //                    else
        //                        caption = dr["grand_total_field"].ToString().Substring(dr["grand_total_field"].ToString().IndexOf("].[") + 3).TrimEnd(']');
        //                    //xInnerChild.InnerText = "[" + caption + "]";

        //                    if (dtype.ToLower() == "double")
        //                        formula = "\"" + currency + " \"+" + " Sum([" + caption + "])";//caption setCaption(lblReportSrc.Text, dr["subtotal_field"].ToString(), "")
        //                    else if (dtype.ToLower() == "decimal")
        //                        formula = "Format(Sum([" + caption + "])," + "\"0.00\")";//caption
        //                    else
        //                        formula = "Sum([" + caption + "])";//caption

        //                    //if (dr["grand_total_field"].ToString().IndexOf("].[") == -1)
        //                    //    formula = "Format(Sum(" + caption + ")," + "\"0.00\")"; //dr["grand_total_field"].ToString()
        //                    //else
        //                    //    formula = "Format(Sum(" + caption + ")," + "\"0.00\")";//dr["grand_total_field"].ToString().Substring(dr["grand_total_field"].ToString().IndexOf("].[") + 3).TrimEnd(']')
        //                }
        //                xInnerChild.InnerText = formula;
        //                xChild.AppendChild(xInnerChild);
        //                formula = "";

        //                xInnerChild = xDoc.CreateElement("Left");
        //                xInnerChild.InnerText = hsRptLocations[dr["grand_total_field"].ToString()].ToString();
        //                xChild.AppendChild(xInnerChild);
        //                xInnerChild = xDoc.CreateElement("Calculated");
        //                xInnerChild.InnerText = "true";
        //                xChild.AppendChild(xInnerChild);
        //                xInnerChild = xDoc.CreateElement("Width");
        //                if (lblReportSrc.Text.ToLower() == "sql")
        //                {
        //                    if (dr["grand_total_field"].ToString().IndexOf("].[") == -1)
        //                        xInnerChild.InnerText = hsReportWidth[dr["grand_total_field"].ToString()].ToString();
        //                    else
        //                        xInnerChild.InnerText = hsReportWidth[dr["grand_total_field"].ToString().Substring(dr["grand_total_field"].ToString().IndexOf("].[") + 3).TrimEnd(']')].ToString();
        //                }
        //                else
        //                    xInnerChild.InnerText = hsReportWidth[dr["grand_total_field"].ToString()].ToString();

        //                //xInnerChild.InnerText = hsReportWidth[dr["grand_total_field"].ToString()].ToString(); //"1000";
        //                xChild.AppendChild(xInnerChild);
        //                xInnerChild = xDoc.CreateElement("Height");
        //                xInnerChild.InnerText = "300";
        //                xChild.AppendChild(xInnerChild);
        //                xInnerChild = xDoc.CreateElement("Align");
        //                xInnerChild.InnerText = "8";
        //                xChild.AppendChild(xInnerChild);

        //                //Font
        //                xInnerChild = xDoc.CreateElement("Font");
        //                xNode = xDoc.CreateElement("Bold");
        //                xNode.InnerText = "true";
        //                xInnerChild.AppendChild(xNode);
        //                xNode = xDoc.CreateElement("Name");
        //                xNode.InnerText = "Arial";
        //                xInnerChild.AppendChild(xNode);
        //                xNode = xDoc.CreateElement("Size");
        //                xNode.InnerText = "8";
        //                xInnerChild.AppendChild(xNode);
        //                xChild.AppendChild(xInnerChild);
        //                xParent.AppendChild(xChild);
        //                idx++;
        //            }
        //        }
        //    }
        //    dtG = null;
        //    #endregion

        //    #region Header Text
        //    if (txtHeaderText.Text.Trim() != "")
        //    {
        //        xChild = xDoc.CreateElement("Field");
        //        xInnerChild = xDoc.CreateElement("Name");
        //        xInnerChild.InnerText = "lblHdrField";
        //        xChild.AppendChild(xInnerChild);
        //        xInnerChild = xDoc.CreateElement("Section");
        //        xInnerChild.InnerText = "1";
        //        xChild.AppendChild(xInnerChild);
        //        xInnerChild = xDoc.CreateElement("Text");
        //        xInnerChild.InnerText = txtHeaderText.Text;
        //        xChild.AppendChild(xInnerChild);
        //        xInnerChild = xDoc.CreateElement("Width");
        //        xInnerChild.InnerText = getLength(txtHeaderText.Text).ToString();
        //        xChild.AppendChild(xInnerChild);
        //        xInnerChild = xDoc.CreateElement("Height");
        //        xInnerChild.InnerText = "300";
        //        xChild.AppendChild(xInnerChild);
        //        xInnerChild = xDoc.CreateElement("Left");
        //        xInnerChild.InnerText = "10";
        //        xChild.AppendChild(xInnerChild);
        //        xInnerChild = xDoc.CreateElement("Top");
        //        xInnerChild.InnerText = "1050";
        //        xChild.AppendChild(xInnerChild);

        //        //Font
        //        xInnerChild = xDoc.CreateElement("Font");
        //        xNode = xDoc.CreateElement("Bold");
        //        xNode.InnerText = "-1";
        //        xInnerChild.AppendChild(xNode);
        //        xNode = xDoc.CreateElement("Name");
        //        xNode.InnerText = "Arial";
        //        xInnerChild.AppendChild(xNode);
        //        xNode = xDoc.CreateElement("Size");
        //        xNode.InnerText = "10";
        //        xInnerChild.AppendChild(xNode);

        //        xChild.AppendChild(xInnerChild);
        //        xParent.AppendChild(xChild);
        //    }

        //    #endregion

        //    #region Footer Text
        //    if (txtFooterText.Text.Trim() != "")
        //    {
        //        xChild = xDoc.CreateElement("Field");
        //        xInnerChild = xDoc.CreateElement("Name");
        //        xInnerChild.InnerText = "lblFooField";
        //        xChild.AppendChild(xInnerChild);
        //        xInnerChild = xDoc.CreateElement("Section");
        //        xInnerChild.InnerText = "4";
        //        xChild.AppendChild(xInnerChild);
        //        xInnerChild = xDoc.CreateElement("Text");
        //        xInnerChild.InnerText = txtFooterText.Text;
        //        xChild.AppendChild(xInnerChild);
        //        xInnerChild = xDoc.CreateElement("Width");
        //        xInnerChild.InnerText = getLength(txtFooterText.Text).ToString();
        //        xChild.AppendChild(xInnerChild);
        //        xInnerChild = xDoc.CreateElement("Height");
        //        xInnerChild.InnerText = "300";
        //        xChild.AppendChild(xInnerChild);
        //        xInnerChild = xDoc.CreateElement("Left");
        //        xInnerChild.InnerText = "10";
        //        xChild.AppendChild(xInnerChild);
        //        xParent.AppendChild(xChild);
        //    }
        //    #endregion

        //    #region Display Date
        //    if (chkDisplayDate.Checked == true)
        //    {
        //        xChild = xDoc.CreateElement("Field");
        //        xInnerChild = xDoc.CreateElement("Name");
        //        xInnerChild.InnerText = "lblDateField";
        //        xChild.AppendChild(xInnerChild);
        //        xInnerChild = xDoc.CreateElement("Section");
        //        xInnerChild.InnerText = "4";
        //        xChild.AppendChild(xInnerChild);
        //        xInnerChild = xDoc.CreateElement("Text");
        //        xInnerChild.InnerText = DateTime.Now.ToShortDateString();
        //        xChild.AppendChild(xInnerChild);
        //        xInnerChild = xDoc.CreateElement("Width");
        //        xInnerChild.InnerText = "1100";
        //        xChild.AppendChild(xInnerChild);
        //        xInnerChild = xDoc.CreateElement("Height");
        //        xInnerChild.InnerText = "300";
        //        xChild.AppendChild(xInnerChild);
        //        xInnerChild = xDoc.CreateElement("Left");
        //        xInnerChild.InnerText = (reportWidth - 1100).ToString();
        //        xChild.AppendChild(xInnerChild);
        //        xParent.AppendChild(xChild);
        //    }
        //    #endregion

        //    #region Display Page Number
        //    if (chkDisplayPageNum.Checked == true)
        //    {
        //        xChild = xDoc.CreateElement("Field");
        //        xInnerChild = xDoc.CreateElement("Name");
        //        xInnerChild.InnerText = "lblPageNoField";
        //        xChild.AppendChild(xInnerChild);
        //        xInnerChild = xDoc.CreateElement("Section");
        //        xInnerChild.InnerText = "4";
        //        xChild.AppendChild(xInnerChild);
        //        xInnerChild = xDoc.CreateElement("Text");
        //        xInnerChild.InnerText = "\"Page\"" + " & [Page] &  " + "\" of \"" + " & [Pages]";
        //        xChild.AppendChild(xInnerChild);
        //        xInnerChild = xDoc.CreateElement("Width");
        //        xInnerChild.InnerText = "3360";
        //        xChild.AppendChild(xInnerChild);
        //        xInnerChild = xDoc.CreateElement("Height");
        //        xInnerChild.InnerText = "300";
        //        xChild.AppendChild(xInnerChild);
        //        xInnerChild = xDoc.CreateElement("Left");
        //        xInnerChild.InnerText = ((reportWidth / 2) - (1680)).ToString();
        //        xChild.AppendChild(xInnerChild);
        //        xInnerChild = xDoc.CreateElement("Calculated");
        //        xInnerChild.InnerText = "true";
        //        xChild.AppendChild(xInnerChild);
        //        xInnerChild = xDoc.CreateElement("Align");
        //        xInnerChild.InnerText = "7";
        //        xChild.AppendChild(xInnerChild);
        //        xParent.AppendChild(xChild);
        //    }
        //    #endregion

        //    reportNode.AppendChild(xParent);
        //    xDoc.DocumentElement.AppendChild(reportNode);
        //    hsRptLocations = null;
        //    hsDupFields = null;

        //    //xDoc.Save(Server.MapPath(".") + "\\report\\reportxml.xml");
        //    string fileName = "";
        //    if (txtRepName.Text.Trim() == "")
        //    {
        //        fileName = "NewReport";
        //        reportViewer.Report.Load(xDoc, "New Report");
        //    }
        //    else
        //    {
        //        fileName = txtRepName.Text;
        //        reportViewer.Report.Load(xDoc, txtRepName.Text);
        //    }

        //    //DataTable resDt = hdd.GetDataTable(sql);
        //    //reportViewer.Report.DataSource.Recordset = resDt;

        //    #region Export section
        //    if (exportFlag)
        //    {
        //        MemoryStream memStream = new MemoryStream();
        //        Response.ClearContent();
        //        Response.ClearHeaders();
        //        switch (exportFormat.ToUpper().Trim())
        //        {
        //            case "XLS":
        //                reportViewer.Report.RenderToStream(memStream, C1.C1Report.FileFormatEnum.Excel);
        //                Response.ContentType = "application/xls";
        //                fileName += ".xls";
        //                break;
        //            case "PDF":
        //                reportViewer.Report.RenderToStream(memStream, C1.C1Report.FileFormatEnum.PDF);
        //                Response.ContentType = "application/pdf";
        //                fileName += ".pdf";
        //                break;
        //            case "RTF":
        //                reportViewer.Report.RenderToStream(memStream, C1.C1Report.FileFormatEnum.RTF);
        //                Response.ContentType = "application/rtf";
        //                fileName += ".rtf";
        //                break;
        //            case "HTML":
        //                reportViewer.Report.RenderToStream(memStream, C1.C1Report.FileFormatEnum.HTMLPaged);
        //                Response.ContentType = "application/htm";
        //                fileName += ".htm";
        //                break;
        //            default:
        //                reportViewer.Report.RenderToStream(memStream, C1.C1Report.FileFormatEnum.Excel);
        //                Response.ContentType = "application/xls";
        //                fileName += ".xls";
        //                break;
        //        }
        //        byte[] bArray = memStream.ToArray();
        //        Response.AddHeader("content-disposition", "attachment;filename=\"" + fileName + "\"");
        //        Response.BinaryWrite(bArray);
        //        bArray = null;
        //        memStream.Close();
        //        memStream.Flush();
        //        memStream = null;
        //    }
        //    #endregion

        //    if (Session["xdoc"] == null)
        //        Session.Add("xdoc", xDoc);
        //    hsFieldNames = null;
        //    xDoc = null;
        //}
        //catch (Exception ex)
        //{
        //    LogWriter.WriteLog("generateReport : Error: " + ex.Message);
        //}
        //finally
        //{
        //    xDoc = null;
        //}
        //return isGenerated;
        #endregion
        
    }

    /// <summary>
    /// To create a new column in DataTable where is has a URL information for HyperLink.
    /// </summary>
    /// <param name="dt">DataTable for the Report Page/Fields.</param>
    /// <param name="dsReport">DataSet which contains Reports information.</param>
    private bool LinkSet(DataTable dtReportPage, DataSet dsReport) //Added by 'Imran Gani' on 10/02/2012 to add New column in dt for Hyperlink.
    {
        DataSet dsTemp = new DataSet();
        string strPagesetRowId = string.Empty, strMenuRowId = string.Empty, sql = string.Empty;
        bool ret = false;
        try
        {
            string sTempUrl = HttpContext.Current.Request.Url.AbsoluteUri.Substring(0, HttpContext.Current.Request.Url.AbsoluteUri.LastIndexOf('/') + 1);
            DataRow drFirstCol = dsReport.Tables["p_sy_report_att"].Select("attrib_sequence='0'")[0];
            //Get the Column Name of new column in DataTable. syntax Ex: name_af_row_id.
            string strTempCol = drFirstCol["attrib_id"].ToString() + "_" + drFirstCol["af_row_id"].ToString();
            string strObjId = drFirstCol["object_id"].ToString();

            if (dsReport.Tables["p_sy_report"].Rows[0]["rpt_base_object"].ToString().ToLower() == "object")
            {
                //sql = "Select pageset_id from sy_pgs where af_row_id = (Select pageset_id from sy_pgs_mem where object_id='" + strObjId + "')";
                sql = "Select pageset_id from sy_pgs_mem where object_id='" + strObjId + "';";
                strPagesetRowId = hdd.GetColumnValue(sql);
                if (strPagesetRowId == null || strPagesetRowId == "")
                    return ret;
            }
            // Below else condition added by 'Imran Gani' on 02/05/12, to set the HyperLink for query report.
            else if (dsReport.Tables["p_sy_report"].Rows[0]["rpt_base_object"].ToString().ToLower() == "sql")
            {
                sql = "Select primary_Object_id from sy_report_sql where report_base_id='" + strObjId + "'";
                strObjId = hdd.GetColumnValue(sql);
                if (strObjId != null && strObjId != "")
                {
                    //sql = "Select pageset_id from sy_pgs where af_row_id = (Select pageset_id from sy_pgs_mem where object_id=(select object_id from sy_obj where af_row_id = '" + strObjId + "' ))";
                    sql = "Select pageset_id from sy_pgs_mem where object_id=(select object_id from sy_obj where af_row_id = '" + strObjId + "');";
                    strPagesetRowId = hdd.GetColumnValue(sql);
                    if (strPagesetRowId == null || strPagesetRowId == "")
                        return ret;
                }
                else
                    return ret;
            }
            else
                return ret;

            sql = "Select * from sy_mnu mn inner join sy_rol_acc rol_acc on rol_acc.menu_id=mn.af_row_id and rol_acc.role_id ='" + Session["roleid"].ToString() + "' and rol_acc.is_accessible=1 and mn.pageset_id = '" + strPagesetRowId + "' order by is_active desc; Select * from sy_mnu mn inner join sy_rol_acc rol_acc on rol_acc.menu_id=mn.af_row_id and mn.pageset_id = '" + strPagesetRowId + "' and mn.is_active=1;";
            dsTemp = hdd.GetDataset(sql);
            if (dsTemp.Tables[0] != null && dsTemp.Tables[0].Rows.Count != 0)
                strMenuRowId = dsTemp.Tables[0].Rows[0]["af_row_id"].ToString(); // To get menu information depends on user accessable.
            else if (dsTemp.Tables[1] != null && dsTemp.Tables[1].Rows.Count != 0)
                strMenuRowId = dsTemp.Tables[1].Rows[0]["af_row_id"].ToString(); // To get menu information which does not have user accessable.
            else
                return ret;

            string strEditPage = getEditPage(dsTemp); // To get page name

            if (!dtReportPage.Columns.Contains(strTempCol))
            {
                DataColumn dc = new DataColumn(strTempCol);
                dc.Expression = "\'" + sTempUrl + strEditPage + "?pgs_id=" + strPagesetRowId + "&PK=\'+af_row_id+\'&mn=" + strMenuRowId + "&VMODE=1\'";
                dtReportPage.Columns.Add(dc);
            }
            else
                dtReportPage.Columns[strTempCol].Expression = "\'" + sTempUrl + strEditPage + "?pgs_id=" + strPagesetRowId + "&PK=\'+af_row_id+\'&mn=" + strMenuRowId + "&VMODE=1\'";
            
            dtReportPage.AcceptChanges();
            ret = true;
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("LinkSet Error : " + ex.Message);
        }
        finally
        {
            dsTemp.Dispose();
        }
        return ret;
    }
    /// <summary>
    /// To get page information which has to be execute once it got triggered.
    /// </summary>
    /// <param name="dsTemp">DataSet which should have information of menu table.</param>
    /// <returns>Page Name</returns>
    private string getEditPage(DataSet dsTemp) //Added this function from GenerateGrid.cs and altered by 'Imran Gani' on 10/02/2012
    {
        string sRet = "DynamicScreen.aspx"; //by default it will be "DynamicScreen.aspx"
        DataRow dr = null;
        if (dsTemp.Tables[0] != null && dsTemp.Tables[0].Rows.Count != 0)
            dr = dsTemp.Tables[0].Rows[0]; // To get menu information depends on user accessable.
        else
            dr = dsTemp.Tables[1].Rows[0]; // To get menu information which does not have user accessable.

        if (dr != null)
            if (dr["pageset_url_type"].ToString() == "2")
            {
                sRet = dr["pageset_url"].ToString();
            }
            else if (dr["pageset_url_type"].ToString() == "4") // Added by srivatsan for transaction document
            {
                sRet = "TransDoc.aspx";
            }
        return sRet;
    }

    private string getSqlForObjects()
    {
        string sSql = "";
        if (dsReport.Tables["p_sy_report"].Rows[0]["rpt_base_object"].ToString().ToLower() == "sql")
        {
            string sSqlId = dsReport.Tables["p_sy_report_obj"].Rows[0]["object_id"].ToString();
            sSql = getPredefinedSQL(sSqlId);
        }
        else
        {
            string sTableName = getObjectName(dsReport.Tables["p_sy_report_obj"].Rows[0]["object_id"].ToString());
            string sFieldName = getFieldNamesForObjects(dsReport.Tables["p_sy_report_att"], sTableName);            
            if (sFieldName != "")
                sSql = "Select " + sFieldName + " from " + sTableName;
            sSql = sSql + getWhereCondForObj(sTableName); //" where 1=1"); // Modified by Imran Gani on 20-Jul-2012, for Source Filter.
        }

        return sSql;
    }

    private string getFieldNamesForObjects(DataTable dtAttribute, string sObjectName)
    {
        string sFields = "";

        DataTable dtMasterDetail = new DataTable();
        dtMasterDetail = getMasterDetail(dsReport.Tables["p_sy_report_obj"].Rows[0]["object_id"].ToString());
        
        foreach (DataRow dr in dtAttribute.Rows)
        {
            string sAttrib_id = dr["attrib_name"].ToString().Replace(' ', '_');

            #region Value conversions
            if (sAttrib_id.ToLower() == "created_at" || sAttrib_id.ToLower() == "modified_at")
            {
                DataTable dtZone = new DataTable();
                string tQry = "select utc_offset from sy_timezone where timezone_id = (select time_zone from sy_usr where af_row_id='" + Session["user_afrowid"].ToString() + "')";
                dtZone = hdd.GetDataTable(tQry);
                if (dtZone.Rows.Count > 0)
                {
                    string offset = dtZone.Rows[0]["utc_offset"].ToString();
                    if (offset.IndexOf(".") != -1)
                    {
                        int mins = Convert.ToInt32(offset.Substring(offset.IndexOf(".") + 1));
                        int hrs = Convert.ToInt32(offset.Substring(0, offset.IndexOf(".")));
                        sFields += "(select dateadd(minute," + mins.ToString() + ",dateadd(hour," + hrs.ToString() + "," + sAttrib_id + "))) as [" + sAttrib_id + "],";
                    }
                    else
                        sFields += "(select dateadd(hour," + offset + "," + sAttrib_id + ")) as [" + sAttrib_id + "],";
                }
                else
                    sFields += "[" + sAttrib_id + "] as [" + sAttrib_id + "],";
                dtZone = null;
            }
            //created/modified timezone conversion
            else if (sAttrib_id.ToLower() == "created_by" || sAttrib_id.ToLower() == "modified_by" || sAttrib_id.ToLower() == "owner_id")
            {
                //string objName = dr["attrib_id"].ToString().Substring(0, dr["attrib_id"].ToString().IndexOf("]")).Replace("[", "").Replace("]", "");
                sFields = sFields + "(" + getOwnerName(sAttrib_id, sObjectName) + ") as [" + sAttrib_id + "],";
            }
            else if (dtMasterDetail.Rows.Count > 0)
            {
                if (sAttrib_id.Trim() == "")
                {
                    DataRow drR = hdd.GetTableRow("select * from sy_obj_att where af_row_id='" + dr["attrib_id"].ToString() + "'");
                    if (drR != null)
                    {
                        sAttrib_id = drR["attrib_id"].ToString();
                        dr["attrib_name"] = sAttrib_id;
                    }
                    drR = null;
                }
                DataRow[] drF = dtMasterDetail.Select("attrib_id='" + sAttrib_id + "'");
                if (drF.Length > 0)
                {
                    string parentName = hdd.GetColumnValue("select object_table from sy_obj where object_id='" + drF[0]["master_obj"].ToString() + "'");
                    sFields = sFields + "(select top 1 [" + drF[0]["display_att"].ToString() + "] from " + parentName + " where af_row_id=" + sObjectName + "." + sAttrib_id + ") as [" +  sAttrib_id + "],";
                }
                else
                    sFields = sFields + " [" + sObjectName + "].[" + sAttrib_id + "],";
                drF = null;
            }
            #endregion
            else
                sFields = sFields + " [" + sObjectName + "].[" + sAttrib_id + "],"; //+ "] as [" + dr["caption"].ToString() + "], " ;
        }
        dtMasterDetail = null;
        sFields = sFields.Trim();

        if (!sFields.Contains(" [" + sObjectName + "].[af_row_id]")) // Added by 'Imran Gani' on 09/02/2012 for HyperLink requirement.
            sFields = sFields + " [" + sObjectName + "].[af_row_id],";

        if (sFields.EndsWith(","))
            sFields = sFields.Trim(',');
        return sFields;
    }
    //---Commented for changing reporting control from component one to asp.net reporting control
    /// <summary>
    /// function is used to generate report in XML document.
    /// </summary>
    /// <returns>true/false</returns>
    //private bool generateReport(bool exportFlag, string exportFormat)
    //{
    //    if (wz_Report.ActiveStepIndex < 4) return true;

    //    if (dsReport == null)
    //    {
    //        cancelClick(); 
    //        return false;
    //    }
    //    if (dsReport.Tables.Count == 0)
    //    {
    //        cancelClick();
    //        return false;
    //    }

    //    bool isGenerated = true;
    //    XmlDocument xDoc = new XmlDocument();
    //    int reportWidth = 10;
    //    XmlElement xNode = null, xParent = null, xChild = null, xInnerChild = null;
    //    Hashtable hsStyle = null;
    //    Hashtable hsReportWidth = new Hashtable();
    //    Hashtable hsDupFields = new Hashtable();
    //    Hashtable hsFieldNames = new Hashtable();

    //    try
    //    {
    //        hsStyle = getCSSProperies(".Grid_Report_Header");
    //        reportViewer.BorderWidth = Unit.Point(1);
    //        reportViewer.BorderColor = System.Drawing.Color.FromName(hsStyle["BackgroundColor"].ToString());
    //        reportViewer.BackColor = System.Drawing.Color.White;
    //        reportViewer.NavigationBar.Style.BorderWidth = Unit.Point(1);
    //        reportViewer.NavigationBar.Style.BorderColor = System.Drawing.Color.FromName(hsStyle["BackgroundColor"].ToString());

    //        hsStyle = getCSSProperies(".Grid_Row1");
    //        string alColor = hsStyle["BackgroundColor"].ToString();
    //        reportViewer.NavigationBar.Style.BackColor = System.Drawing.Color.FromName(alColor);
            
    //        //reportViewer.NavigationBar.Style.Font.Size = FontUnit.Point(8);
    //        //reportViewer.NavigationBar.Style.CssClass = "controlFont";            
    //        hsStyle = null;

    //        XmlDeclaration xDec = xDoc.CreateXmlDeclaration("1.0", "utf-8", "yes");

    //        XmlElement rootNode = xDoc.CreateElement("Reports");
    //        xDoc.AppendChild(rootNode);

    //        XmlElement reportNode = xDoc.CreateElement("Report");

    //        #region Report Information
    //        DataTable dt = dsReport.Tables["p_sy_report"];
    //        if (dt.Rows.Count == 0)
    //        {
    //            xNode = xDoc.CreateElement("Name");
    //            xNode.InnerText = "New Report";
    //            reportNode.AppendChild(xNode);

    //            xParent = xDoc.CreateElement("ReportInfo");
    //            xChild = xDoc.CreateElement("Title");
    //            xChild.InnerText = "NOT SPECIFIED";
    //            xParent.AppendChild(xChild);
    //            reportNode.AppendChild(xParent);
    //        }
    //        else
    //        {
    //            xNode = xDoc.CreateElement("Name");
    //            if (txtRepName.Text.Trim() == "")
    //                xNode.InnerText = "New Report";
    //            else
    //                xNode.InnerText = txtRepName.Text;
    //            reportNode.AppendChild(xNode);

    //            xParent = xDoc.CreateElement("ReportInfo");
    //            xChild = xDoc.CreateElement("Title");
    //            if (txtRepTitle.Text.Trim() == "")
    //                xChild.InnerText = "NOT SPECIFIED";
    //            else
    //                xChild.InnerText = txtRepTitle.Text;
    //            xParent.AppendChild(xChild);
    //            reportNode.AppendChild(xParent);
    //        }
    //        #endregion

    //        Localization loc = new Localization();
    //        string sDateTimeFormatString = loc.getDateTimeFormat();
    //        string sDateFormatString = loc.getDateFormat();            
    //        loc = null;

    //        #region Assigning DataSource - object or query
    //        if (Session["dbcon"] == null)
    //        {
    //            LogWriter.WriteLog("generateReport : Error : connection string is empty");
    //            return false;
    //        }

    //        DataTable dtTmp = null;
    //        string sql = "", cols = "", tabName = "";

    //        if (lblReportSrc.Text.ToLower() == "object")
    //        {
    //            dtTmp = hdd.GetDataTable("select [object_name]obj_name, object_table from sy_obj where [object_id]='" + cmbObjects.SelectedValue.Substring(cmbObjects.SelectedValue.IndexOf("@") + 1) + "'");
    //            if (dtTmp.Rows.Count > 0)
    //                tabName = dtTmp.Rows[0]["object_table"].ToString();
    //        }
    //        else if (lblReportSrc.Text.ToLower() == "sql")
    //        {
    //            string sqlParam = "";
    //            dtTmp = hdd.GetDataTable("select report_base_sql, report_base_param from sy_report_sql where report_base_id='" + cmbObjects.SelectedValue.Substring(cmbObjects.SelectedValue.IndexOf("@") + 1) + "'");
    //            if (dtTmp.Rows.Count > 0)
    //            {
    //                sql = dtTmp.Rows[0]["report_base_sql"].ToString();
    //                sqlParam = dtTmp.Rows[0]["report_base_param"].ToString();
    //            }
    //            else
    //            {
    //                LogWriter.WriteLog("generateReport : Error : Table/Query object is empty");
    //                return false;
    //            }

    //            if (hiddenParam.Value == "P") //parameterized query
    //            {
                    
    //                Hashtable hsParamNew = new Hashtable();
    //                if (Session["param"] == null)
    //                    hsParamNew = updateParameters(sql, sqlParam);
    //                else
    //                    hsParamNew = (Hashtable)Session["param"];

    //                if (hsParamNew.Count == 0)
    //                {
    //                    createParameters();
    //                    hsParamNew = updateParameters(sql, sqlParam);
    //                }
    //                //if default value is present then generate with default values

    //                if (Session["showReport"] == null)
    //                {
    //                    setVisibleValue(false);
    //                    return true;
    //                }
    //                else if (Convert.ToBoolean(Session["showReport"].ToString()) == false)
    //                {
    //                    setVisibleValue(false);
    //                    return true;
    //                }
    //                else
    //                    setVisibleValue(true);

    //                if (hsParamNew.Count > 0)
    //                {
    //                    BuildParameters bpObj = new BuildParameters();
    //                    sql = bpObj.makeSQL(hsParamNew, sql);
    //                    bpObj = null;
    //                }
    //                //foreach (string sParam in hsParamNew.Keys)
    //                //{
    //                //    if (sqlParam.Trim() != "")
    //                //    {
    //                //        //string tmpP = "$" + sParam.Substring(0, sParam.LastIndexOf("[")).Replace("[", "").Replace("]", "") + "$";
    //                //        //string outVal = checkSingleQuote(tmpP, hsParamNew[sParam].ToString(), sql);
    //                //        //sql = sql.Replace(tmpP, outVal);//hsParamNew[sParam].ToString()
    //                //        string tmpP = "$" + sParam.Substring(0, sParam.LastIndexOf("[")).Replace("[", "").Replace("]", "") + "$";
    //                //        string outVal = checkSingleQuote(tmpP, hsParamNew[sParam].ToString(), sql);
    //                //        sql = sql.Replace(tmpP, outVal);//hsParamNew[sParam].ToString()

    //                //        tmpP = "#" + sParam.Substring(0, sParam.LastIndexOf("[")).Replace("[", "").Replace("]", "") + "#";
    //                //        outVal = checkSingleQuote(tmpP, hsParamNew[sParam].ToString(), sql);
    //                //        sql = sql.Replace(tmpP, outVal);//hsParamNew[sParam].ToString()
    //                //    }
    //                //    else
    //                //        sql = sql.Replace(sParam, hsParamNew[sParam].ToString());
    //                //}
    //                hsParamNew = null;
    //            }
    //        }
    //        dtTmp = null;

    //        dt = dsReport.Tables["p_sy_report_att"];
    //        if (!IsEdit && dt != null)
    //        {
    //            if (dt.Columns.Contains("af_row_id"))
    //            {
    //                if (dt.Select("af_row_id <> '' Or af_row_id is not null").Length != dt.Rows.Count)
    //                    dt.Rows.Clear();
    //            }
    //            else
    //                dt.Rows.Clear();
    //        }
    //        if (dt == null)
    //        {
    //            collect_step_values(1);
    //            dt = dsReport.Tables["p_sy_report_att"];
    //        }
    //        if (dt != null)
    //        {
    //            if (dt.Rows.Count == 0)
    //            {
    //                dsReport = collect_step_values(1);
    //                dt = dsReport.Tables["p_sy_report_att"];
    //            }

    //            if (dt.Rows.Count != lstSelectedFields1.Items.Count)
    //            {
    //                if (!IsEdit)
    //                    dt.Rows.Clear();
    //                collect_step_values(1);
    //            }
    //            else if (dt.Rows.Count == lstSelectedFields1.Items.Count)
    //            {
    //                DataTable dtR = dt.Clone();
    //                for (int iCount = 0; iCount < lstSelectedFields1.Items.Count; iCount++)
    //                {
    //                    ListItem li = lstSelectedFields1.Items[iCount];
    //                    DataRow[] drF = dt.Select("attrib_id='" + li.Value + "'");
    //                    if (drF.Length > 0)
    //                        dtR.ImportRow(drF[0]);
    //                    else
    //                    {
    //                        if (li.Value.IndexOf("].[") != -1)
    //                        {
    //                            drF = dt.Select("attrib_id='" + li.Value.Substring(li.Value.IndexOf("].[") + 3).Replace("]", "") + "'");
    //                            if (drF.Length > 0)
    //                                dtR.ImportRow(drF[0]);
    //                        }
    //                    }
    //                    drF = null;
    //                }
    //                dt.Rows.Clear();
    //                dt.Merge(dtR);
    //                dtR.Rows.Clear();
    //                dtR = null;
    //            }
    //            if (dt.Rows.Count == 0)
    //                collect_step_values(1);

    //            if (lblReportSrc.Text.ToLower() == "object")
    //            {
    //                DataTable dtBind = getBindList(cmbObjects.SelectedValue.Substring(cmbObjects.SelectedValue.IndexOf("@") + 1));
    //                DataTable dtMasDetail = getMasterDetail(cmbObjects.SelectedValue.Substring(cmbObjects.SelectedValue.IndexOf("@") + 1));

    //                foreach (DataRow dr in dt.Rows)
    //                {
    //                    DataRow[] drT = dt.Select("caption='" + dr["caption"].ToString() + "'");
    //                    if (drT.Length > 1)
    //                    {
    //                        if (hsDupFields.ContainsKey(dr["caption"].ToString()))
    //                            hsDupFields[dr["caption"].ToString()] = Convert.ToInt32(hsDupFields[dr["caption"].ToString()]) + 1;
    //                        else
    //                            hsDupFields.Add(dr["caption"].ToString(), 1);
    //                    }
    //                    else
    //                        hsDupFields.Add(dr["caption"].ToString(), 1);
    //                    drT = null;

    //                    string caption = setCaption(lblReportSrc.Text, dr["attrib_id"].ToString(), dr["caption"].ToString()) + hsDupFields[dr["caption"].ToString()];
    //                    hsFieldNames.Add(dr["attrib_id"].ToString(), caption);

    //                    if (caption.Trim() == "")
    //                    {
    //                        DataRow[] drF = dtMasDetail.Select("attrib_id='" + dr["attrib_id"].ToString().Substring(dr["attrib_id"].ToString().IndexOf("].[") + 3).TrimEnd(']') + "'");
    //                        if (drF.Length > 0)
    //                            caption = drF[0]["display_att"].ToString();
    //                        drF = null;
    //                    }

    //                    if (dr["attrib_id"].ToString().IndexOf("].[") == -1)
    //                    {
    //                        cols += "[" + getAttribId(lblReportSrc.Text, dr["attrib_id"].ToString()) + "] as [" + caption + "],";
    //                    }
    //                    else
    //                    {
    //                        string attrib_id = getAttribId(lblReportSrc.Text, dr["attrib_id"].ToString().Substring(dr["attrib_id"].ToString().IndexOf("].[") + 3).TrimEnd(']'));

    //                        if (dtMasDetail.Rows.Count > 0)
    //                        {
    //                            DataRow[] drF = dtMasDetail.Select("attrib_id='" + attrib_id.Trim() + "'");
    //                            string tName = hdd.GetColumnValue("select object_table from sy_obj where object_id='" + drF[0]["master_obj"].ToString() + "'");
    //                            cols += "(select top 1 " + drF[0]["display_att"].ToString() + " from " + tName + " where af_row_id=" + tabName + "." + attrib_id + ") as [" + caption + "],";
    //                            dtMasDetail.Rows.Clear();
    //                        }
    //                        else if (dtBind.Select("control_attrib_id='" + attrib_id + "'").Length > 0)
    //                        {
    //                            DataRow[] drF = dtBind.Select("control_attrib_id='" + attrib_id + "'");
    //                            //(select top 1 emp_lname + '  ' + emp_fname from ap_emp as A where A.emp_id=ap_emp.report_emp_id)as report_emp_id
    //                            if (drF[0]["bind_table"].ToString().IndexOf(",") == -1)
    //                                cols += "(select top 1 " + drF[0]["bind_text"].ToString() + " from " + drF[0]["bind_table"].ToString() + " As BT1 where BT1.[" + drF[0]["bind_value"].ToString() + "]=[" + tabName + "].[" + attrib_id + "]) as [" + caption + "],";
    //                            else//multi tables in bind_table
    //                            {
    //                                //(select top 1 customer_name from bu_customer A,bu_program B where A.customer_id = B.customer_id and A.customer_id=2)
    //                                string[] tables = drF[0]["bind_table"].ToString().Split(',');
    //                                cols += "(select top 1 " + drF[0]["bind_text"].ToString() + " from ";
    //                                string tmpStr = "";
    //                                Hashtable hsTmp = new Hashtable();
    //                                for (int i = 0; i < tables.Length; i++)
    //                                {
    //                                    tmpStr += tables[i] + " As BT" + (i + 1) + ",";
    //                                    hsTmp.Add(tables[i], "BT" + (i + 1));
    //                                }
    //                                cols += tmpStr.TrimEnd(',');
    //                                tmpStr = drF[0]["bind_parameter"].ToString();
    //                                if (tmpStr.Trim() != "")
    //                                {
    //                                    foreach (string key in hsTmp.Keys)
    //                                        tmpStr = tmpStr.Replace(key, hsTmp[key].ToString());
    //                                    cols += " where " + tmpStr + " and " + drF[0]["bind_value"].ToString() + "=[" + tabName + "].[" + attrib_id + "]) as [" + caption + "],";
    //                                }
    //                                else
    //                                    cols += " where " + drF[0]["bind_value"].ToString() + "=[" + tabName + "].[" + attrib_id + "]) as [" + caption + "],";
    //                                hsTmp = null;
    //                            }
    //                        }
    //                        //createdby/modifiedby conversion
    //                        else if (attrib_id.ToLower() == "created_at" || attrib_id.ToLower() == "modified_at")
    //                        {
    //                            DataTable dtZone = new DataTable();
    //                            string tQry = "select utc_offset from sy_timezone where timezone_id = (select time_zone from sy_usr where af_row_id='" + Session["user_afrowid"].ToString() + "')";
    //                            dtZone = hdd.GetDataTable(tQry);
    //                            if (dtZone.Rows.Count > 0)
    //                            {
    //                                string offset = dtZone.Rows[0]["utc_offset"].ToString();
    //                                if (offset.IndexOf(".") != -1)
    //                                {
    //                                    int mins = Convert.ToInt32(offset.Substring(offset.IndexOf(".") + 1));
    //                                    int hrs = Convert.ToInt32(offset.Substring(0, offset.IndexOf(".")));
    //                                    cols += "(select dateadd(minute," + mins.ToString() + ",dateadd(hour," + hrs.ToString() + "," + attrib_id + "))) as [" + caption + "],";
    //                                }
    //                                else
    //                                    cols += "(select dateadd(hour," + offset + "," + attrib_id + ")) as [" + caption + "],";
    //                            }
    //                            else
    //                                cols += "[" + attrib_id + "] as [" + caption + "],";
    //                            dtZone = null;
    //                        }
    //                        //created/modified timezone conversion
    //                        else if (attrib_id.ToLower() == "created_by" || attrib_id.ToLower() == "modified_by" || attrib_id.ToLower() == "owner_id")
    //                        {
    //                            string objName = dr["attrib_id"].ToString().Substring(0, dr["attrib_id"].ToString().IndexOf("]")).Replace("[", "").Replace("]", "");
    //                            cols += "(" + getOwnerName(attrib_id, objName) + ") as [" + caption + "],";
    //                        }
    //                        else
    //                            cols += "[" + attrib_id + "] as [" + caption + "],";
    //                    }
    //                    caption = "";
    //                }
    //                sql = "select " + cols.TrimEnd(',') + " from " + tabName;
    //                dtBind = null;
    //            }
    //        }
    //        else
    //        {
    //            if (lblReportSrc.Text.ToLower() == "object")
    //            {
    //                DataTable dtBind = getBindList(cmbObjects.SelectedValue.Substring(cmbObjects.SelectedValue.IndexOf("@") + 1));
    //                DataTable dtMasDetail = getMasterDetail(cmbObjects.SelectedValue.Substring(cmbObjects.SelectedValue.IndexOf("@") + 1));

    //                //cols += "[" + getAttribId(lblReportSrc.Text, li.Value.Substring(li.Value.IndexOf("].[") + 3).TrimEnd(']')) + "] as [" + caption + "],";
    //                foreach (ListItem li in lstSelectedFields1.Items)
    //                {
    //                    DataRow[] drT = dt.Select("caption='" + li.Value.ToString() + "'");
    //                    if (drT.Length > 1)
    //                    {
    //                        if (hsDupFields.ContainsKey(li.Value.ToString()))
    //                            hsDupFields[li.Value.ToString()] = Convert.ToInt32(hsDupFields[li.Value.ToString()]) + 1;
    //                        else
    //                            hsDupFields.Add(li.Value.ToString(), 1);
    //                    }
    //                    else
    //                        hsDupFields.Add(li.Value.ToString(), 1);
    //                    drT = null;

    //                    string caption = setCaption(lblReportSrc.Text, li.Value.ToString(), "") + hsDupFields[li.Value.ToString()];
    //                    hsFieldNames.Add(li.Value.ToString(), caption);
    //                    if (caption.Trim() == "")
    //                    {
    //                        DataRow[] drF = dtMasDetail.Select("attrib_id='" + li.Value.Substring(li.Value.IndexOf("].[") + 3).TrimEnd(']') + "'");
    //                        if (drF.Length > 0)
    //                            caption = drF[0]["display_att"].ToString();
    //                        drF = null;
    //                    }
    //                    if (li.Value.IndexOf("].[") == -1)
    //                        cols += "[" + getAttribId(lblReportSrc.Text, li.Value) + "] as [" + li.Text + "],";
    //                    else
    //                    {
    //                        string attrib_id = getAttribId(lblReportSrc.Text, getAttribId(lblReportSrc.Text, li.Value.Substring(li.Value.IndexOf("].[") + 3).TrimEnd(']')));

    //                        if (dtMasDetail.Select("attrib_id='" + li.Value.Substring(li.Value.IndexOf("].[") + 3).TrimEnd(']') + "'").Length > 0)
    //                        {
    //                            DataRow[] drF = dtMasDetail.Select("attrib_id='" + li.Value.Substring(li.Value.IndexOf("].[") + 3).TrimEnd(']') + "'");
    //                            string tName = hdd.GetColumnValue("select object_table from sy_obj where object_id='" + drF[0]["master_obj"].ToString() + "'");
    //                            cols += "(select top 1 " + drF[0]["display_att"].ToString() + " from " + tName + " where af_row_id=" + tabName + "." + attrib_id + ") as [" + caption + "],";
    //                        }
    //                        else if (dtBind.Select("control_attrib_id='" + attrib_id + "'").Length > 0)
    //                        {
    //                            DataRow[] drF = dtBind.Select("control_attrib_id='" + attrib_id + "'");
    //                            //(select top 1 emp_lname + '  ' + emp_fname from ap_emp as A where A.emp_id=ap_emp.report_emp_id)as report_emp_id
    //                            if (drF[0]["bind_table"].ToString().IndexOf(",") == -1)
    //                                cols += "(select top 1 " + drF[0]["bind_text"].ToString() + " from " + drF[0]["bind_table"].ToString() + " As BT1 where BT1." + drF[0]["bind_value"].ToString() + "=" + tabName + "." + attrib_id + ") as [" + caption + "],";
    //                            else//multi tables in bind_table
    //                            {
    //                                //(select top 1 customer_name from bu_customer A,bu_program B where A.customer_id = B.customer_id and A.customer_id=2)
    //                                string[] tables = drF[0]["bind_table"].ToString().Split(',');
    //                                cols += "(select top 1 " + drF[0]["bind_text"].ToString() + " from ";
    //                                string tmpStr = "";
    //                                Hashtable hsTmp = new Hashtable();
    //                                for (int i = 0; i < tables.Length; i++)
    //                                {
    //                                    tmpStr += tables[i] + " As BT" + (i + 1) + ",";
    //                                    hsTmp.Add(tables[i], "BT" + (i + 1));
    //                                }
    //                                cols += tmpStr.TrimEnd(',');
    //                                tmpStr = drF[0]["bind_parameter"].ToString();
    //                                if (tmpStr.Trim() != "")
    //                                {
    //                                    foreach (string key in hsTmp.Keys)
    //                                        tmpStr = tmpStr.Replace(key, hsTmp[key].ToString());
    //                                    cols += " where " + tmpStr + " and " + drF[0]["bind_value"].ToString() + "=" + tabName + "." + attrib_id + ") as [" + caption + "],";
    //                                }
    //                                else
    //                                    cols += " where " + drF[0]["bind_value"].ToString() + "=" + tabName + "." + attrib_id + ") as [" + caption + "],";
    //                                hsTmp = null;
    //                            }
    //                        }
    //                        //createdby/modifiedby conversion
    //                        else if (attrib_id.ToLower() == "created_at" || attrib_id.ToLower() == "modified_at")
    //                        {
    //                            DataTable dtZone = new DataTable();
    //                            string tQry = "select utc_offset from sy_timezone where timezone_id = (select time_zone from sy_usr where af_row_id='" + Session["user_afrowid"].ToString() + "')";
    //                            dtZone = hdd.GetDataTable(tQry);
    //                            if (dtZone.Rows.Count > 0)
    //                            {
    //                                string offset = dtZone.Rows[0]["utc_offset"].ToString();
    //                                if (offset.IndexOf(".") != -1)
    //                                {
    //                                    int mins = Convert.ToInt32(offset.Substring(offset.IndexOf(".") + 1));
    //                                    int hrs = Convert.ToInt32(offset.Substring(0, offset.IndexOf(".")));
    //                                    cols += "(select dateadd(minute," + mins.ToString() + ",dateadd(hour," + hrs.ToString() + "," + attrib_id + "))) as [" + caption + "],";
    //                                }
    //                                else
    //                                    cols += "(select dateadd(hour," + offset + "," + attrib_id + ")) as [" + caption + "],";
    //                            }
    //                            else
    //                                cols += "[" + attrib_id + "] as [" + caption + "],";
    //                            dtZone = null;
    //                        }
    //                        //created/modified timezone conversion
    //                        else if (attrib_id.ToLower() == "created_by" || attrib_id.ToLower() == "modified_by" || attrib_id.ToLower() == "owner_id")
    //                        {
    //                            string objName = li.Value.Substring(0, li.Value.IndexOf("]")).Replace("[", "").Replace("]", "");
    //                            cols += "(" + getOwnerName(attrib_id, objName) + ") as [" + caption + "],";
    //                        }
    //                        else
    //                            cols += "[" + attrib_id + "] as [" + caption + "],";
    //                    }                            
    //                    caption = "";
    //                }
    //                sql = "select " + cols.TrimEnd(',') + " from " + tabName;
    //            }

    //            createDataTable(1, ref dsReport);
    //            dt = dsReport.Tables["p_sy_report_att"];
    //            fillSelectedValues(ref dt);
    //        }

    //        //applying security
    //        if (lblReportSrc.Text.ToLower() == "object")
    //        {
    //            if (getWhereCondition() == "")
    //                sql += " where 1=1";
    //            else
    //                sql += " where " + getWhereCondition();
    //        }
    //        xParent = xDoc.CreateElement("DataSource");
    //        xChild = xDoc.CreateElement("ConnectionString");
    //        xChild.InnerText = makeOLEDBConnectionString(Session["dbcon"].ToString());
    //        xParent.AppendChild(xChild);
    //        xNode = xDoc.CreateElement("RecordSource");
    //        xNode.InnerText = sql;
    //        xParent.AppendChild(xNode);
    //        reportNode.AppendChild(xParent);            
    //        #endregion
            
    //        if (checkData(sql))
    //            lnkExport.Enabled = true;
    //        else
    //            lnkExport.Enabled = false;

    //        Hashtable hsDt = new Hashtable();
    //        if (lblReportSrc.Text.ToLower() == "sql")
    //            hsDt = getSqlDataTypes(sql);

    //        string currency = getCurrency(Session["user_afrowid"].ToString());

    //        #region Layout information
    //        //Calculating width
    //        hsReportWidth.Clear();
    //        int minWidth = 3500;
    //        reportWidth = 0;
    //        if (lblReportSrc.Text.ToLower() == "object")
    //        {
    //            for (int i = 0; i < dt.Rows.Count; i++)
    //            {
    //                int width = getFieldLengthForObject(dt.Rows[i]["attrib_id"].ToString(), cmbObjects.SelectedValue.Substring(cmbObjects.SelectedValue.IndexOf("@") + 1), tabName);
    //                hsReportWidth.Add(dt.Rows[i]["attrib_id"].ToString(), width);
    //                reportWidth += width;
    //            }
    //        }
    //        else
    //        {
    //            hsReportWidth = getFieldLengthForQuery(sql, cmbObjects.SelectedValue.Substring(cmbObjects.SelectedValue.IndexOf("@") + 1), hsDt);
    //            foreach(string key in hsReportWidth.Keys)
    //                reportWidth += Convert.ToInt32(hsReportWidth[key].ToString());                
    //        }

    //        reportWidth += hsReportWidth.Count * 50;//space width needs to be added
    //        if (reportWidth <= minWidth)
    //            reportWidth = reportWidth + minWidth; 
    //        xParent = xDoc.CreateElement("Layout");
    //        xChild = xDoc.CreateElement("Width");
    //        xChild.InnerText = (reportWidth).ToString();
    //        xParent.AppendChild(xChild);
            
    //        xNode = xDoc.CreateElement("Orientation");
    //        xNode.InnerText = "2";
    //        xParent.AppendChild(xNode);

    //        xNode = xDoc.CreateElement("PaperSize");
    //        xNode.InnerText = "5";
    //        xParent.AppendChild(xNode);
    //        reportNode.AppendChild(xParent);

    //        xParent = xDoc.CreateElement("Font");
    //        xChild = xDoc.CreateElement("Name");
    //        xChild.InnerText = "Arial";
    //        xParent.AppendChild(xChild);
    //        xChild = xDoc.CreateElement("Size");
    //        xChild.InnerText = "10";
    //        xParent.AppendChild(xChild);
    //        reportNode.AppendChild(xParent);

    //        xNode = xDoc.CreateElement("OnOpen");
    //        xNode.InnerText = "' -- style script start " + Convert.ToChar(13) + Convert.ToChar(10) + "_styleCtr = 0 " + Convert.ToChar(13) + Convert.ToChar(10) + "' -- style script end";
    //        reportNode.AppendChild(xNode);

    //        xNode = xDoc.CreateElement("GrowShrinkMode");
    //        xNode.InnerText = "1";
    //        reportNode.AppendChild(xNode);

    //        #endregion

    //        #region Grouping Sections
            
    //        xParent = xDoc.CreateElement("Groups");

    //        //xWriter.WriteStartElement("Groups");
    //        DataTable dtG = dsReport.Tables["p_report_grouping"];
    //        if (dtG == null)
    //            dtG = new DataTable();
    //        for (int i = 0; i < dtG.Rows.Count; i++)
    //        {
    //            DataRow dr = dtG.Rows[i];
    //            xChild = xDoc.CreateElement("Group");
    //            xInnerChild = xDoc.CreateElement("Name");
    //            xInnerChild.InnerText = "Group" + (i + 1).ToString();
    //            xChild.AppendChild(xInnerChild);
    //            //Group by

    //            xInnerChild = xDoc.CreateElement("GroupBy");
    //            string caption = "";

    //            ////get caption from attribute
    //            //if (dsReport.Tables.Contains("p_sy_report_att"))
    //            //{
    //            //    DataRow[] drF = dsReport.Tables["p_sy_report_att"].Select("attrib_id='" + dr["grouping_field"].ToString() + "'");
    //            //    if (drF.Length > 0)
    //            //        caption = drF[0]["caption"].ToString();
    //            //    drF = null;
    //            //}
    //            //else
    //            //    caption = setCaption(lblReportSrc.Text, dr["grouping_field"].ToString(), "");

    //            if (lblReportSrc.Text.ToLower() == "object")
    //                //caption = "[" + caption + "]";
    //                caption = "[" + hsFieldNames[dr["grouping_field"].ToString()].ToString() + "]";
    //            else if (lblReportSrc.Text.ToLower() == "sql")
    //            {
    //                if (dr["grouping_field"].ToString().IndexOf("].[") == -1)
    //                    caption = dr["grouping_field"].ToString();
    //                else
    //                    caption = dr["grouping_field"].ToString().Substring(dr["grouping_field"].ToString().IndexOf("].[") + 3).TrimEnd(']');
    //            }
    //            xInnerChild.InnerText = caption;
    //            xChild.AppendChild(xInnerChild);

    //            xInnerChild = xDoc.CreateElement("Sort");                
    //            xInnerChild.InnerText = dr["grouping_order"].ToString().ToLower() == "ascending" ? "1" : "2";
    //            xChild.AppendChild(xInnerChild);

    //            xParent.AppendChild(xChild);
    //            dr = null;
    //        }
    //        dtG = null;

    //        reportNode.AppendChild(xParent);
    //        #endregion

    //        #region Sections
    //        xParent = xDoc.CreateElement("Sections");

    //        //Detail section
    //        xChild = xDoc.CreateElement("Section");
    //        xInnerChild = xDoc.CreateElement("Name");
    //        xInnerChild.InnerText = "Detail";
    //        xChild.AppendChild(xInnerChild);
    //        xInnerChild = xDoc.CreateElement("Type");
    //        xInnerChild.InnerText = "0";
    //        xChild.AppendChild(xInnerChild);
    //        xInnerChild = xDoc.CreateElement("Height");
    //        xInnerChild.InnerText = "300";
    //        xChild.AppendChild(xInnerChild);

    //        hsStyle = getCSSProperies(".Grid_Row1");
    //        alColor = hsStyle["BackgroundColor"].ToString();
    //        alColor = "\"" + alColor + "\"";
    //        xNode = xDoc.CreateElement("OnPrint");
    //        //xNode.InnerText = "' -- style script start " + Convert.ToChar(13) + Convert.ToChar(10) + " detail.BackColor = iif(_styleCtr mod 2 = 0, rgb(255,255,255), rgb(197,242,171)) " + Convert.ToChar(13) + Convert.ToChar(10) + "_styleCtr = _styleCtr + 1 " + Convert.ToChar(13) + Convert.ToChar(10) + "' -- style script end";//191,219 //228,240,255
    //        xNode.InnerText = "' -- style script start " + Convert.ToChar(13) + Convert.ToChar(10) + " detail.BackColor = iif(_styleCtr mod 2 = 0," + "\"#FFFFFF\"" + ", " +  alColor + ")" + Convert.ToChar(13) + Convert.ToChar(10) + "_styleCtr = _styleCtr + 1 " + Convert.ToChar(13) + Convert.ToChar(10) + "' -- style script end";//191,219 //228,240,255
    //        xChild.AppendChild(xNode);
    //        xParent.AppendChild(xChild);

    //        //Header section
    //        xChild = xDoc.CreateElement("Section");
    //        xInnerChild = xDoc.CreateElement("Name");
    //        xInnerChild.InnerText = "Header";
    //        xChild.AppendChild(xInnerChild);
    //        xInnerChild = xDoc.CreateElement("Type");
    //        xInnerChild.InnerText = "1";
    //        xChild.AppendChild(xInnerChild);
    //        xInnerChild = xDoc.CreateElement("Height");
    //        if (txtHeaderText.Text.Trim() == "")
    //            xInnerChild.InnerText = "1360";
    //        else
    //            xInnerChild.InnerText = "1000";
    //        xChild.AppendChild(xInnerChild);
    //        xInnerChild = xDoc.CreateElement("Repeat");
    //        xInnerChild.InnerText = "-1";
    //        xChild.AppendChild(xInnerChild);

    //        string sTemp = HttpContext.Current.Request.Url.AbsoluteUri.Substring(0, HttpContext.Current.Request.Url.AbsoluteUri.LastIndexOf("/"));

    //        string customlogo = getLogo();
    //        if (customlogo.Trim() != "")
    //            sTemp = sTemp + "/" + customlogo;
    //        else
    //        {
    //            sTemp = sTemp + "/images/" + HttpContext.Current.Session["theme"].ToString().ToLower().Replace("theme", "");
    //            sTemp = sTemp + "/logo.gif";
    //        }

    //        xNode = xDoc.CreateElement("OnPrint");
    //        xNode.InnerText = "logoField.Picture=\"" + sTemp + "\"" ;
    //        xChild.AppendChild(xNode);
    //        xParent.AppendChild(xChild);

    //        //Footer
    //        xChild = xDoc.CreateElement("Section");
    //        xInnerChild = xDoc.CreateElement("Name");
    //        xInnerChild.InnerText = "Footer";
    //        xChild.AppendChild(xInnerChild);
    //        xInnerChild = xDoc.CreateElement("Type");
    //        xInnerChild.InnerText = "2";
    //        xChild.AppendChild(xInnerChild);
    //        xInnerChild = xDoc.CreateElement("Height");
    //        xInnerChild.InnerText = "300";
    //        xChild.AppendChild(xInnerChild);
    //        xParent.AppendChild(xChild);

    //        //Page Header
    //        hsStyle = getCSSProperies(".Grid_Header");
    //        xChild = xDoc.CreateElement("Section");
    //        xInnerChild = xDoc.CreateElement("Name");
    //        xInnerChild.InnerText = "PageHeader";
    //        xChild.AppendChild(xInnerChild);
    //        xInnerChild = xDoc.CreateElement("Type");
    //        xInnerChild.InnerText = "3";
    //        xChild.AppendChild(xInnerChild);
    //        xInnerChild = xDoc.CreateElement("Height");
    //        xInnerChild.InnerText = "300";
    //        xChild.AppendChild(xInnerChild);
    //        xInnerChild = xDoc.CreateElement("BackColor");
    //        xInnerChild.InnerText = hsStyle["BackgroundColor"].ToString(); //"16431752";
    //        xChild.AppendChild(xInnerChild);
    //        xInnerChild = xDoc.CreateElement("Repeat");
    //        xInnerChild.InnerText = "-1";
    //        xChild.AppendChild(xInnerChild);
    //        xParent.AppendChild(xChild);
    //        hsStyle = null;
    //        //PageFooter
    //        xChild = xDoc.CreateElement("Section");
    //        xInnerChild = xDoc.CreateElement("Name");
    //        xInnerChild.InnerText = "PageFooter";
    //        xChild.AppendChild(xInnerChild);
    //        xInnerChild = xDoc.CreateElement("Type");
    //        xInnerChild.InnerText = "4";
    //        xChild.AppendChild(xInnerChild);
    //        xInnerChild = xDoc.CreateElement("Height");
    //        xInnerChild.InnerText = "300";
    //        xChild.AppendChild(xInnerChild);
    //        xParent.AppendChild(xChild);

    //        //Grouping Header/Footer Sections
    //        DataTable dtS = dsReport.Tables["p_report_grouping"];
    //        int sec = 5;
    //        if (dtS == null)
    //            dtS = new DataTable();
    //        for (int k = 0; k < dtS.Rows.Count; k++)
    //        {
    //            DataRow dr = dt.Rows[k];
    //            //Group Header 
    //            xChild = xDoc.CreateElement("Section");
    //            xInnerChild = xDoc.CreateElement("Name");
    //            xInnerChild.InnerText = "Group" + (k + 1).ToString() + "_Header";
    //            xChild.AppendChild(xInnerChild);
    //            xInnerChild = xDoc.CreateElement("Type");
    //            xInnerChild.InnerText = sec.ToString();
    //            xChild.AppendChild(xInnerChild);
    //            xInnerChild = xDoc.CreateElement("Height");
    //            xInnerChild.InnerText = "300";
    //            xChild.AppendChild(xInnerChild);
    //            xParent.AppendChild(xChild);
               
    //            sec++;

    //            //Group Footer
    //            xChild = xDoc.CreateElement("Section");
    //            xInnerChild = xDoc.CreateElement("Name");
    //            xInnerChild.InnerText = "Group" + (k + 1).ToString() + "_Footer";
    //            xChild.AppendChild(xInnerChild);
    //            xInnerChild = xDoc.CreateElement("Type");
    //            xInnerChild.InnerText = sec.ToString();
    //            xChild.AppendChild(xInnerChild);
    //            xInnerChild = xDoc.CreateElement("Height");
    //            xInnerChild.InnerText = "300";
    //            xChild.AppendChild(xInnerChild);
    //            xParent.AppendChild(xChild);
    //            sec++;
    //        }            
    //        reportNode.AppendChild(xParent);
    //        #endregion

    //        #region Report Title
    //        xParent = xDoc.CreateElement("Fields");
    //        //Detail section
    //        xChild = xDoc.CreateElement("Field");
    //        xInnerChild = xDoc.CreateElement("Name");
    //        xInnerChild.InnerText = "title";
    //        xChild.AppendChild(xInnerChild);

    //        xInnerChild = xDoc.CreateElement("Section");
    //        xInnerChild.InnerText = "1";
    //        xChild.AppendChild(xInnerChild);

    //        string tmp = txtRepTitle.Text.Trim() == "" ? cmbObjects.SelectedItem.Text : txtRepTitle.Text; //"Untitled Report"
    //        if (tmp == cmbObjects.SelectedItem.Text) //"Untitled Report")
    //        {
    //            if (txtRepName.Text.Trim() != "" )
    //                tmp = txtRepName.Text;
    //        }
    //        xInnerChild = xDoc.CreateElement("Text");
    //        xInnerChild.InnerText = tmp;
    //        xChild.AppendChild(xInnerChild);

    //        xInnerChild = xDoc.CreateElement("Height");
    //        xInnerChild.InnerText = "400";
    //        xChild.AppendChild(xInnerChild);

    //        xInnerChild = xDoc.CreateElement("Left");
    //        if (chkDisplayLogo.Checked)
    //            xInnerChild.InnerText = ((((reportWidth / 2) - (getLength(tmp) / 2)) + 1500).ToString());
    //        else
    //            xInnerChild.InnerText = ((reportWidth / 2) - (getLength(tmp) / 2)).ToString();
    //        xChild.AppendChild(xInnerChild);

    //        xInnerChild = xDoc.CreateElement("Width");
    //        xInnerChild.InnerText = getLength(tmp).ToString();
    //        xChild.AppendChild(xInnerChild);

    //        xInnerChild = xDoc.CreateElement("Top");
    //        xInnerChild.InnerText = "300";
    //        xChild.AppendChild(xInnerChild);

    //        xInnerChild = xDoc.CreateElement("Align");
    //        xInnerChild.InnerText = "6";
    //        xChild.AppendChild(xInnerChild);

    //        xInnerChild = xDoc.CreateElement("WordWrap");
    //        xInnerChild.InnerText = "0";
    //        xChild.AppendChild(xInnerChild);

    //        hsStyle = getCSSProperies(".pgForm_title");
    //        xInnerChild = xDoc.CreateElement("ForeColor");
    //        xInnerChild.InnerText = hsStyle["Color"].ToString(); // "16711680";
    //        xChild.AppendChild(xInnerChild);
    //        //Font
    //        xInnerChild = xDoc.CreateElement("Font");
    //        xNode = xDoc.CreateElement("Bold");
    //        xNode.InnerText = "-1";
    //        xInnerChild.AppendChild(xNode);
    //        xNode = xDoc.CreateElement("Name");
    //        xNode.InnerText = "Arial";
    //        xInnerChild.AppendChild(xNode);
    //        xNode = xDoc.CreateElement("Size");
    //        xNode.InnerText = hsStyle["FontSize"].ToString();
    //        xInnerChild.AppendChild(xNode);

    //        xChild.AppendChild(xInnerChild);
    //        xParent.AppendChild(xChild);
    //        hsStyle = null;
    //        #endregion            

    //        #region Report Labels/Captions
    //        int left = 50;
    //        int idx = 1;
    //        hsStyle = getCSSProperies(".Grid_Report_Header");
    //        Hashtable hsCaption = new Hashtable();
    //        foreach (DataRow dr in dt.Rows)
    //        {                
    //            xChild = xDoc.CreateElement("Field");

    //            xInnerChild = xDoc.CreateElement("Name");
    //            xInnerChild.InnerText = "lbl" + idx.ToString();
    //            xChild.AppendChild(xInnerChild);

    //            xInnerChild = xDoc.CreateElement("Section");
    //            xInnerChild.InnerText = "3";
    //            xChild.AppendChild(xInnerChild);

    //            xInnerChild = xDoc.CreateElement("Text");                
    //            string caption = setCaption(lblReportSrc.Text, dr["attrib_id"].ToString(), dr["caption"].ToString());
    //            hsCaption.Add(dr["attrib_id"].ToString(), dr["caption"].ToString());
    //            xInnerChild.InnerText = caption;
    //            caption = "";
    //            xChild.AppendChild(xInnerChild);

    //            xInnerChild = xDoc.CreateElement("Left");
    //            xInnerChild.InnerText = left.ToString();
    //            xChild.AppendChild(xInnerChild);
    //            xInnerChild = xDoc.CreateElement("Width");
    //            if (lblReportSrc.Text.ToLower() == "sql")
    //            {
    //                if (dr["attrib_id"].ToString().IndexOf("].[") == -1)
    //                    xInnerChild.InnerText = hsReportWidth[dr["attrib_id"].ToString()].ToString();
    //                else
    //                    xInnerChild.InnerText = hsReportWidth[dr["attrib_id"].ToString().Substring(dr["attrib_id"].ToString().IndexOf("].[") + 3).TrimEnd(']')].ToString();
    //            }
    //            else
    //                xInnerChild.InnerText = hsReportWidth[dr["attrib_id"].ToString()].ToString();

    //            xChild.AppendChild(xInnerChild);
    //            xInnerChild = xDoc.CreateElement("CanGrow");
    //            xInnerChild.InnerText = "-1";
    //            xChild.AppendChild(xInnerChild);
    //            xInnerChild = xDoc.CreateElement("Height");
    //            xInnerChild.InnerText = "300";
    //            xChild.AppendChild(xInnerChild);
    //            xInnerChild = xDoc.CreateElement("ForeColor");
    //            xInnerChild.InnerText = hsStyle["Color"].ToString();// "16777215";
    //            xChild.AppendChild(xInnerChild);

    //            xInnerChild = xDoc.CreateElement("Align");
    //            if (lblReportSrc.Text.ToLower() == "object")
    //                xInnerChild.InnerText = getAttribAlignment(lblReportSrc.Text, dr["attrib_id"].ToString());
    //            else if (lblReportSrc.Text.ToLower() == "sql")
    //                xInnerChild.InnerText = getSqlAlignment(dr["attrib_id"].ToString(), hsDt);

    //            xChild.AppendChild(xInnerChild);
    //            //Wordwrap
    //            xInnerChild = xDoc.CreateElement("WordWrap");

    //            if (dr["is_wrap"].ToString().ToLower() == "yes" || dr["is_wrap"].ToString().ToLower() == "no")
    //                xInnerChild.InnerText = dr["is_wrap"].ToString() == "Yes" ? "true" : "No";
    //            else
    //            {
    //                if (Convert.ToBoolean(dr["is_wrap"].ToString()) == true)
    //                    xInnerChild.InnerText = "true";
    //                else
    //                    xInnerChild.InnerText = "false";
    //            }
    //            xChild.AppendChild(xInnerChild);

    //            //Font
    //            xInnerChild = xDoc.CreateElement("Font");
    //            xNode = xDoc.CreateElement("Bold");
    //            xNode.InnerText = "true";
    //            //if (dr["is_bold"].ToString().ToLower() == "yes" || dr["is_bold"].ToString().ToLower() == "no")
    //            //    xNode.InnerText = (dr["is_bold"].ToString() == "Yes" ? "true" : "No");
    //            //else
    //            //{
    //            //    if (Convert.ToBoolean(dr["is_bold"].ToString()) == true)
    //            //        xNode.InnerText = "true";
    //            //    else
    //            //        xNode.InnerText = "false";
    //            //}
    //            xInnerChild.AppendChild(xNode);

    //            xNode = xDoc.CreateElement("Name");
    //            xNode.InnerText = "Arial";
    //            xInnerChild.AppendChild(xNode);

    //            xNode= xDoc.CreateElement("Size");
    //            xNode.InnerText = hsStyle["FontSize"].ToString();
    //            xInnerChild.AppendChild(xNode);

    //            xChild.AppendChild(xInnerChild);
    //            xParent.AppendChild(xChild);

    //            if (lblReportSrc.Text.ToLower() == "sql")
    //            {
    //                if (dr["attrib_id"].ToString().IndexOf("].[") == -1)
    //                    left += (Convert.ToInt32(hsReportWidth[dr["attrib_id"].ToString()].ToString()) + 50);
    //                else
    //                    left += (Convert.ToInt32(hsReportWidth[dr["attrib_id"].ToString().Substring(dr["attrib_id"].ToString().IndexOf("].[") + 3).TrimEnd(']')].ToString()) + 50);
    //            }
    //            else
    //                left += (Convert.ToInt32(hsReportWidth[dr["attrib_id"].ToString()].ToString()) + 50);
    //            idx++;
    //        }
    //        #endregion
            
    //        #region Report Fields/Values
    //        left = 50;
    //        idx = 1;           
    //        Hashtable hsRptLocations = new Hashtable();
    //        //hsDupFields.Clear();
    //        foreach (DataRow dr in dt.Rows)
    //        {
    //            xChild = xDoc.CreateElement("Field");

    //            xInnerChild = xDoc.CreateElement("Name");
    //            xInnerChild.InnerText = "Field" + idx.ToString();
    //            xChild.AppendChild(xInnerChild);

    //            xInnerChild = xDoc.CreateElement("Section");
    //            xInnerChild.InnerText = "0";
    //            xChild.AppendChild(xInnerChild);

    //            xInnerChild = xDoc.CreateElement("Text");                

    //            string caption = "";
    //            if (lblReportSrc.Text.ToLower() == "object")
    //            {
    //                caption = "[" + hsFieldNames[dr["attrib_id"].ToString()].ToString() + "]";
    //                //caption = "[" + setCaption(lblReportSrc.Text, dr["attrib_id"].ToString(), dr["caption"].ToString()) + hsDupFields[dr["caption"].ToString()].ToString() + "]";
    //            }
    //            else if (lblReportSrc.Text.ToLower() == "sql")
    //            {
    //                if (dr["attrib_id"].ToString().IndexOf("].[") == -1)
    //                    caption = dr["attrib_id"].ToString();
    //                else
    //                    caption = dr["attrib_id"].ToString().Substring(dr["attrib_id"].ToString().IndexOf("].[") + 3).TrimEnd(']');
    //            }
    //            xInnerChild.InnerText = caption;
    //            xChild.AppendChild(xInnerChild);

    //            string formatSyntax = "";
    //            if (lblReportSrc.Text.ToLower() == "object")
    //            {
    //                string dType = getDataType(dr["attrib_id"].ToString());
    //                if (dType == "DA")
    //                    formatSyntax = sDateFormatString;
    //                else if (dType == "DT")
    //                    formatSyntax = sDateTimeFormatString;
    //                else if (dType == "CU")
    //                    formatSyntax = "#,##0.00";
    //            }
    //            else if (lblReportSrc.Text.ToLower() == "sql")
    //            {
    //                string dType = getSqlDataType(dr["attrib_id"].ToString(), hsDt);
    //                switch(dType.ToLower())
    //                {
    //                    case "date":
    //                        formatSyntax = sDateFormatString;
    //                        break;
    //                    case "datetime":
    //                        formatSyntax = sDateTimeFormatString;
    //                        break;
    //                    case "decimal":
    //                    case "double":
    //                        formatSyntax = "#,##0.00";
    //                        break;
    //                }
    //            }
    //            xInnerChild = xDoc.CreateElement("Format");
    //            xInnerChild.InnerText = formatSyntax;
    //            xChild.AppendChild(xInnerChild);

    //            xInnerChild = xDoc.CreateElement("Left");
    //            xInnerChild.InnerText = left.ToString();
    //            xChild.AppendChild(xInnerChild);
    //            hsRptLocations.Add(dr["attrib_id"], left);
    //            xInnerChild = xDoc.CreateElement("Calculated");
    //            xInnerChild.InnerText = "true";
    //            xChild.AppendChild(xInnerChild);
    //            xInnerChild = xDoc.CreateElement("Width");
    //            //xInnerChild.InnerText = "1000";
    //            //xInnerChild.InnerText = hsReportWidth[dr["attrib_id"].ToString()].ToString();
    //            if (lblReportSrc.Text.ToLower() == "sql")
    //            {
    //                if (dr["attrib_id"].ToString().IndexOf("].[") == -1)
    //                    xInnerChild.InnerText = hsReportWidth[dr["attrib_id"].ToString()].ToString();
    //                else
    //                    xInnerChild.InnerText = hsReportWidth[dr["attrib_id"].ToString().Substring(dr["attrib_id"].ToString().IndexOf("].[") + 3).TrimEnd(']')].ToString();
    //            }
    //            else
    //                xInnerChild.InnerText = hsReportWidth[dr["attrib_id"].ToString()].ToString();

    //            xChild.AppendChild(xInnerChild);
    //            xInnerChild = xDoc.CreateElement("Align");
    //            if (lblReportSrc.Text.ToLower() == "object")
    //                xInnerChild.InnerText = getAttribAlignment(lblReportSrc.Text, dr["attrib_id"].ToString());
    //            else if (lblReportSrc.Text.ToLower() == "sql")
    //                xInnerChild.InnerText = getSqlAlignment(dr["attrib_id"].ToString(), hsDt);
    //            xChild.AppendChild(xInnerChild);

    //            //Wordwrap
    //            xInnerChild = xDoc.CreateElement("WordWrap");
    //            if (dr["is_wrap"].ToString().ToLower() == "yes" || dr["is_wrap"].ToString().ToLower() == "no")
    //                xInnerChild.InnerText = dr["is_wrap"].ToString() == "Yes" ? "true" : "No";
    //            else
    //            {
    //                if (Convert.ToBoolean(dr["is_wrap"].ToString()) == true)
    //                    xInnerChild.InnerText = "true";
    //                else
    //                    xInnerChild.InnerText = "false";
    //            }
    //            xChild.AppendChild(xInnerChild);

    //            xInnerChild = xDoc.CreateElement("CanGrow");
    //            xInnerChild.InnerText = "-1";
    //            xChild.AppendChild(xInnerChild);

    //            xInnerChild = xDoc.CreateElement("Height");
    //            xInnerChild.InnerText = "300";
    //            xChild.AppendChild(xInnerChild);

    //            xInnerChild = xDoc.CreateElement("Font");
    //            //Bold
    //            xNode = xDoc.CreateElement("Bold");
    //            if (dr["is_bold"].ToString().ToLower() == "yes" || dr["is_bold"].ToString().ToLower() == "no")
    //                xNode.InnerText = dr["is_bold"].ToString() == "Yes" ? "true" : "No";
    //            else
    //            {
    //                if (Convert.ToBoolean(dr["is_bold"].ToString()) == true)
    //                    xNode.InnerText = "true";
    //                else
    //                    xNode.InnerText = "false";
    //            }
    //            xInnerChild.AppendChild(xNode);

    //            xNode = xDoc.CreateElement("Name");
    //            xNode.InnerText = "Arial";
    //            xInnerChild.AppendChild(xNode);

    //            xNode = xDoc.CreateElement("Size");
    //            xNode.InnerText = "8";
    //            xInnerChild.AppendChild(xNode);

    //            xChild.AppendChild(xInnerChild);

    //            xParent.AppendChild(xChild);

    //            //left += (Convert.ToInt32(hsReportWidth[dr["attrib_id"].ToString()].ToString())+50);
    //            if (lblReportSrc.Text.ToLower() == "sql")
    //            {
    //                if (dr["attrib_id"].ToString().IndexOf("].[") == -1)
    //                    left += (Convert.ToInt32(hsReportWidth[dr["attrib_id"].ToString()].ToString()) + 50);
    //                else
    //                    left += (Convert.ToInt32(hsReportWidth[dr["attrib_id"].ToString().Substring(dr["attrib_id"].ToString().IndexOf("].[") + 3).TrimEnd(']')].ToString()) + 50);
    //            }
    //            else
    //                left += (Convert.ToInt32(hsReportWidth[dr["attrib_id"].ToString()].ToString()) + 50);
    //            idx++;
    //        }
    //        dt = null;
    //        #endregion

    //        #region Logo/Picture display

    //        if (chkDisplayLogo.Checked)
    //        {
    //            xChild = xDoc.CreateElement("Field");

    //            xInnerChild = xDoc.CreateElement("Name");
    //            xInnerChild.InnerText = "logoField";
    //            xChild.AppendChild(xInnerChild);

    //            xInnerChild = xDoc.CreateElement("Section");
    //            xInnerChild.InnerText = "1";
    //            xChild.AppendChild(xInnerChild);

    //            xInnerChild = xDoc.CreateElement("Left");
    //            xInnerChild.InnerText = "10";
    //            xChild.AppendChild(xInnerChild);

    //            xInnerChild = xDoc.CreateElement("Width");
    //            xInnerChild.InnerText = "3000";
    //            xChild.AppendChild(xInnerChild);

    //            xInnerChild = xDoc.CreateElement("Top");
    //            xInnerChild.InnerText = "0";
    //            xChild.AppendChild(xInnerChild);

    //            xInnerChild = xDoc.CreateElement("Height");
    //            xInnerChild.InnerText = "1000";
    //            xChild.AppendChild(xInnerChild);

    //            xInnerChild = xDoc.CreateElement("PictureAlign");
    //            xInnerChild.InnerText = "7";
    //            xChild.AppendChild(xInnerChild);

    //            //xInnerChild = xDoc.CreateElement("PictureScale");
    //            //xInnerChild.InnerText = "1";
    //            //xChild.AppendChild(xInnerChild);

    //            xParent.AppendChild(xChild);
    //        }
    //        #endregion

    //        #region Report Grouping Header
    //        left = 50;
    //        //Header
    //        dtG = dsReport.Tables["p_report_grouping"];
    //        if (dtG!=null)
    //        {
    //            if (dtG.Rows.Count > 0)
    //            {
    //                dtG = dsReport.Tables["p_report_grouping_header"];
    //                if (dtG == null)
    //                    dtG = new DataTable();
    //                foreach (DataRow dr in dtG.Rows)
    //                {
    //                    //Header Label
    //                    xChild = xDoc.CreateElement("Field");

    //                    xInnerChild = xDoc.CreateElement("Name");
    //                    xInnerChild.InnerText = "Field" + idx.ToString();
    //                    xChild.AppendChild(xInnerChild);

    //                    xInnerChild = xDoc.CreateElement("Section");
    //                    if (dr["group_sequence"].ToString() == "1")
    //                        xInnerChild.InnerText = "5";
    //                    else if (dr["group_sequence"].ToString() == "2")
    //                        xInnerChild.InnerText = "7";
    //                    else if (dr["group_sequence"].ToString() == "3")
    //                        xInnerChild.InnerText = "9";
    //                    xChild.AppendChild(xInnerChild);
    //                    xInnerChild = xDoc.CreateElement("Text");
    //                    string caption = "";

    //                    if (hsCaption.Contains(dr["header_field"].ToString()))
    //                        caption = hsCaption[dr["header_field"].ToString()].ToString();
    //                    else
    //                    {
    //                        if (lblReportSrc.Text.ToLower() == "object")
    //                            caption = setCaption(lblReportSrc.Text, dr["header_field"].ToString(), "");
    //                        else if (lblReportSrc.Text.ToLower() == "sql")
    //                        {
    //                            if (dr["header_field"].ToString().IndexOf("].[") == -1)
    //                                caption = dr["header_field"].ToString();
    //                            else
    //                                caption = dr["header_field"].ToString().Substring(dr["header_field"].ToString().IndexOf("].[") + 3).TrimEnd(']');
    //                        }
    //                    }
    //                    xInnerChild.InnerText = caption;
    //                    //caption = "";
    //                    xChild.AppendChild(xInnerChild);

    //                    xInnerChild = xDoc.CreateElement("Left");
    //                    xInnerChild.InnerText = left.ToString();
    //                    xChild.AppendChild(xInnerChild);
    //                    xInnerChild = xDoc.CreateElement("Calculated");
    //                    xInnerChild.InnerText = "false";
    //                    xChild.AppendChild(xInnerChild);
    //                    xInnerChild = xDoc.CreateElement("Width");

    //                    if (lblReportSrc.Text.ToLower() == "sql")
    //                    {
    //                        if (dr["header_field"].ToString().IndexOf("].[") == -1)
    //                            xInnerChild.InnerText = hsReportWidth[dr["header_field"].ToString()].ToString();
    //                        else
    //                            xInnerChild.InnerText = hsReportWidth[dr["header_field"].ToString().Substring(dr["header_field"].ToString().IndexOf("].[") + 3).TrimEnd(']')].ToString();
    //                    }
    //                    else
    //                        xInnerChild.InnerText = hsReportWidth[dr["header_field"].ToString()].ToString();

    //                    //xInnerChild.InnerText = hsReportWidth[dr["header_field"].ToString()].ToString();
    //                    xChild.AppendChild(xInnerChild);
    //                    xInnerChild = xDoc.CreateElement("Height");
    //                    xInnerChild.InnerText = "300";
    //                    xChild.AppendChild(xInnerChild);
    //                    xInnerChild = xDoc.CreateElement("Align");
    //                    xInnerChild.InnerText = "6";
    //                    xChild.AppendChild(xInnerChild);

    //                    //Font
    //                    xInnerChild = xDoc.CreateElement("Font");
    //                    xNode = xDoc.CreateElement("Bold");
    //                    xNode.InnerText = "true";
    //                    xInnerChild.AppendChild(xNode);
    //                    xNode = xDoc.CreateElement("Name");
    //                    xNode.InnerText = "Arial";
    //                    xInnerChild.AppendChild(xNode);
    //                    xNode = xDoc.CreateElement("Size");
    //                    xNode.InnerText = "8";
    //                    xInnerChild.AppendChild(xNode);
    //                    xNode = xDoc.CreateElement("WordWrap");
    //                    xNode.InnerText = "false";
    //                    xInnerChild.AppendChild(xNode);
    //                    xChild.AppendChild(xInnerChild);
    //                    xParent.AppendChild(xChild);
    //                    left += 1200;
    //                    idx++;

    //                    //Header Field
    //                    xChild = xDoc.CreateElement("Field");
    //                    xInnerChild = xDoc.CreateElement("Name");
    //                    xInnerChild.InnerText = "Field" + idx.ToString();
    //                    xChild.AppendChild(xInnerChild);
    //                    xInnerChild = xDoc.CreateElement("Section");
    //                    if (dr["group_sequence"].ToString() == "1")
    //                        xInnerChild.InnerText = "5";
    //                    else if (dr["group_sequence"].ToString() == "2")
    //                        xInnerChild.InnerText = "7";
    //                    else if (dr["group_sequence"].ToString() == "3")
    //                        xInnerChild.InnerText = "9";
    //                    xChild.AppendChild(xInnerChild);

    //                    xInnerChild = xDoc.CreateElement("Text");
    //                    //caption = "";
    //                    //if (lblReportSrc.Text.ToLower() == "object")
    //                    //    caption = "[" + setCaption(lblReportSrc.Text, dr["header_field"].ToString(), "") + "]";
    //                    //else if (lblReportSrc.Text.ToLower() == "sql")
    //                    //{
    //                    //    if (dr["header_field"].ToString().IndexOf("].[") == -1)
    //                    //        caption = dr["header_field"].ToString();
    //                    //    else
    //                    //        caption = dr["header_field"].ToString().Substring(dr["header_field"].ToString().IndexOf("].[") + 3).TrimEnd(']');
    //                    //}
    //                    if (lblReportSrc.Text.ToLower() == "object")
    //                        xInnerChild.InnerText = "[" + hsFieldNames[dr["header_field"].ToString()].ToString() + "]"; //caption
    //                    else
    //                    {
    //                        if (dr["header_field"].ToString().IndexOf("].[") == -1)
    //                            caption = dr["header_field"].ToString();
    //                        else
    //                            caption = dr["header_field"].ToString().Substring(dr["header_field"].ToString().IndexOf("].[") + 3).TrimEnd(']');
    //                        xInnerChild.InnerText = "[" + caption + "]";
    //                    }
    //                    caption = "";
    //                    xChild.AppendChild(xInnerChild);

    //                    xInnerChild = xDoc.CreateElement("Left");
    //                    xInnerChild.InnerText = left.ToString();
    //                    xChild.AppendChild(xInnerChild);
    //                    xInnerChild = xDoc.CreateElement("Calculated");
    //                    xInnerChild.InnerText = "true";
    //                    xChild.AppendChild(xInnerChild);
    //                    xInnerChild = xDoc.CreateElement("Width");
    //                    //xInnerChild.InnerText = hsReportWidth[dr["header_field"].ToString()].ToString(); //"1000";
    //                    if (lblReportSrc.Text.ToLower() == "sql")
    //                    {
    //                        if (dr["header_field"].ToString().IndexOf("].[") == -1)
    //                            xInnerChild.InnerText = hsReportWidth[dr["header_field"].ToString()].ToString();
    //                        else
    //                            xInnerChild.InnerText = hsReportWidth[dr["header_field"].ToString().Substring(dr["header_field"].ToString().IndexOf("].[") + 3).TrimEnd(']')].ToString();
    //                    }
    //                    else
    //                        xInnerChild.InnerText = hsReportWidth[dr["header_field"].ToString()].ToString();
    //                    xChild.AppendChild(xInnerChild);
    //                    xInnerChild = xDoc.CreateElement("Height");
    //                    xInnerChild.InnerText = "300";
    //                    xChild.AppendChild(xInnerChild);
    //                    xInnerChild = xDoc.CreateElement("Align");
    //                    xInnerChild.InnerText = "6";
    //                    xChild.AppendChild(xInnerChild);

    //                    //Font
    //                    xInnerChild = xDoc.CreateElement("Font");
    //                    xNode = xDoc.CreateElement("Bold");
    //                    xNode.InnerText = "true";
    //                    xInnerChild.AppendChild(xNode);
    //                    xNode = xDoc.CreateElement("Name");
    //                    xNode.InnerText = "Arial";
    //                    xInnerChild.AppendChild(xNode);
    //                    xNode = xDoc.CreateElement("Size");
    //                    xNode.InnerText = "8";
    //                    xInnerChild.AppendChild(xNode);
    //                    xChild.AppendChild(xInnerChild);
    //                    xParent.AppendChild(xChild);

    //                    if (lblReportSrc.Text.ToLower() == "sql")
    //                    {
    //                        if (dr["header_field"].ToString().IndexOf("].[") == -1)
    //                            left += (Convert.ToInt32(hsReportWidth[dr["header_field"].ToString()].ToString()));
    //                        else
    //                            left += (Convert.ToInt32(hsReportWidth[dr["header_field"].ToString().Substring(dr["header_field"].ToString().IndexOf("].[") + 3).TrimEnd(']')].ToString()));
    //                    }
    //                    else
    //                        left += (Convert.ToInt32(hsReportWidth[dr["header_field"].ToString()].ToString()));
    //                    //left += Convert.ToInt32(hsReportWidth[dr["header_field"].ToString()].ToString());// 1200;
    //                    idx++;
    //                }
    //            }
    //        }
    //        dtG = null;
    //        #endregion

    //        #region Report Grouping Subtotal
    //        left = 50;
    //        //Header
    //        dtS = dsReport.Tables["p_report_grouping"];
    //        if (dtS != null)
    //        {
    //            if (dtS.Rows.Count > 0)
    //            {
    //                dtS = dsReport.Tables["p_report_grouping_subtotal"];
    //                if (dtS == null)
    //                    dtS = new DataTable();
    //                foreach (DataRow dr in dtS.Rows)
    //                {
    //                    //Header Label
    //                    xChild = xDoc.CreateElement("Field");
    //                    xInnerChild = xDoc.CreateElement("Name");
    //                    xInnerChild.InnerText = "Field" + idx.ToString();
    //                    xChild.AppendChild(xInnerChild);
    //                    xInnerChild = xDoc.CreateElement("Section");
    //                    if (dr["group_sequence"].ToString() == "1")
    //                        xInnerChild.InnerText = "6";
    //                    else if (dr["group_sequence"].ToString() == "2")
    //                        xInnerChild.InnerText = "8";
    //                    else if (dr["group_sequence"].ToString() == "3")
    //                        xInnerChild.InnerText = "10";
    //                    xChild.AppendChild(xInnerChild);

    //                    xInnerChild = xDoc.CreateElement("Text");
    //                    string formula = "";
    //                    string caption = "";
                        
    //                    if (hsCaption.Contains(dr["subtotal_field"].ToString()))
    //                        caption = hsCaption[dr["subtotal_field"].ToString()].ToString();
    //                    else
    //                        caption = setCaption(lblReportSrc.Text, dr["subtotal_field"].ToString(), "");

    //                    string dtype = getDataType(dr["subtotal_field"].ToString());
    //                    if (lblReportSrc.Text.ToLower() == "object")
    //                    {
    //                        if (dtype == "CU")
    //                            formula = "\"" + currency + " \"+" + " Sum([" + hsFieldNames[dr["subtotal_field"].ToString()].ToString() + "])";//caption setCaption(lblReportSrc.Text, dr["subtotal_field"].ToString(), "")
    //                        else if (dtype == "DC")
    //                            formula = "Format(Sum([" + hsFieldNames[dr["subtotal_field"].ToString()].ToString() + "])," + "\"0.00\")";//caption
    //                        else
    //                            formula = "Sum([" + hsFieldNames[dr["subtotal_field"].ToString()].ToString() + "])";//caption;//#,##0.00
    //                    }
    //                    else if (lblReportSrc.Text.ToLower() == "sql")
    //                    {
    //                        dtype = getSqlDataType(dr["subtotal_field"].ToString(), hsDt);
    //                        //if (dr["subtotal_field"].ToString().IndexOf("].[") == -1)
    //                        //    formula = "Format(Sum(" + caption + ")," + "\"0.00\")";//dr["subtotal_field"].ToString()
    //                        //else
    //                        if (dr["subtotal_field"].ToString().IndexOf("].[") == -1)
    //                            caption = dr["subtotal_field"].ToString();
    //                        else
    //                            caption = dr["subtotal_field"].ToString().Substring(dr["subtotal_field"].ToString().IndexOf("].[") + 3).TrimEnd(']');
    //                        //xInnerChild.InnerText = "[" + caption + "]";

    //                        if (dtype.ToLower() == "double")
    //                            formula = "\"" + currency + " \"+" + " Sum([" + caption + "])";//caption setCaption(lblReportSrc.Text, dr["subtotal_field"].ToString(), "")
    //                        else if (dtype.ToLower() == "decimal")
    //                            formula = "Format(Sum([" + caption + "])," + "\"0.00\")";//caption
    //                        else
    //                            formula = "Sum([" + caption + "])";//caption
    //                        //formula = "Format(Sum(" + caption + ")," + "\"0.00\")"; //dr["subtotal_field"].ToString().Substring(dr["subtotal_field"].ToString().IndexOf("].[") + 3).TrimEnd(']')
    //                    }
    //                    xInnerChild.InnerText = formula;
    //                    formula = "";

    //                    xChild.AppendChild(xInnerChild);
    //                    xInnerChild = xDoc.CreateElement("Left");
    //                    xInnerChild.InnerText = hsRptLocations[dr["subtotal_field"].ToString()].ToString();
    //                    xChild.AppendChild(xInnerChild);
    //                    xInnerChild = xDoc.CreateElement("Calculated");
    //                    xInnerChild.InnerText = "true";
    //                    xChild.AppendChild(xInnerChild);
    //                    xInnerChild = xDoc.CreateElement("Width");
    //                    if (lblReportSrc.Text.ToLower() == "sql")
    //                    {
    //                        if (dr["subtotal_field"].ToString().IndexOf("].[") == -1)
    //                            xInnerChild.InnerText = hsReportWidth[dr["subtotal_field"].ToString()].ToString();
    //                        else
    //                            xInnerChild.InnerText = hsReportWidth[dr["subtotal_field"].ToString().Substring(dr["subtotal_field"].ToString().IndexOf("].[") + 3).TrimEnd(']')].ToString();
    //                    }
    //                    else
    //                        xInnerChild.InnerText = hsReportWidth[dr["subtotal_field"].ToString()].ToString();
    //                    //xInnerChild.InnerText = hsReportWidth[dr["subtotal_field"].ToString()].ToString(); //"1000";
    //                    xChild.AppendChild(xInnerChild);
    //                    xInnerChild = xDoc.CreateElement("Height");
    //                    xInnerChild.InnerText = "300";
    //                    xChild.AppendChild(xInnerChild);
    //                    xInnerChild = xDoc.CreateElement("Align");
    //                    xInnerChild.InnerText = "8";
    //                    xChild.AppendChild(xInnerChild);

    //                    //Font
    //                    xInnerChild = xDoc.CreateElement("Font");
    //                    xNode = xDoc.CreateElement("Bold");
    //                    xNode.InnerText = "true";
    //                    xInnerChild.AppendChild(xNode);
    //                    xNode = xDoc.CreateElement("Name");
    //                    xNode.InnerText = "Arial";
    //                    xInnerChild.AppendChild(xNode);
    //                    xNode = xDoc.CreateElement("Size");
    //                    xNode.InnerText = "8";
    //                    xInnerChild.AppendChild(xNode);
    //                    xChild.AppendChild(xInnerChild);
    //                    xParent.AppendChild(xChild);

    //                    idx++;
    //                }
    //            }
    //        }            
    //        dtS = null;
    //        #endregion

    //        #region Report Grand Total
    //        left = 50;
    //        //Header
    //        dtG = dsReport.Tables["p_report_grouping"];
    //        if (dtG != null)
    //        {
    //            if (dtG.Rows.Count > 0)
    //            {
    //                dtG = dsReport.Tables["p_report_grouping_grand_total"];
    //                if (dtG == null)
    //                    dtG = new DataTable();
    //                foreach (DataRow dr in dtG.Rows)
    //                {
    //                    //Header Label
    //                    xChild = xDoc.CreateElement("Field");
    //                    xInnerChild = xDoc.CreateElement("Name");
    //                    xInnerChild.InnerText = "Field" + idx.ToString();
    //                    xChild.AppendChild(xInnerChild);
    //                    xInnerChild = xDoc.CreateElement("Section");
    //                    xInnerChild.InnerText = "2";
    //                    xChild.AppendChild(xInnerChild);
    //                    xInnerChild = xDoc.CreateElement("Text");
    //                    string formula = "", caption = "";
    //                    string dtype = getDataType(dr["grand_total_field"].ToString());

    //                    if (hsCaption.Contains(dr["grand_total_field"].ToString()))
    //                        caption = hsCaption[dr["grand_total_field"].ToString()].ToString();
    //                    else
    //                        caption = setCaption(lblReportSrc.Text, dr["grand_total_field"].ToString(), "");

    //                    if (lblReportSrc.Text.ToLower() == "object")
    //                    {
    //                        if (dtype == "CU")
    //                            formula = "\"" + currency + " \" +" + "Sum([" + hsFieldNames[dr["grand_total_field"].ToString()].ToString() + "])";//caption
    //                        else if (dtype == "DC")
    //                            formula = "Format(Sum([" + hsFieldNames[dr["grand_total_field"].ToString()].ToString() + "])," + "\"0.00\")"; //caption setCaption(lblReportSrc.Text, dr["grand_total_field"].ToString(), "")
    //                        else
    //                            formula = "Sum([" + hsFieldNames[dr["grand_total_field"].ToString()].ToString() +"])";//caption setCaption(lblReportSrc.Text, dr["grand_total_field"].ToString(), "")
    //                    }
    //                    else if (lblReportSrc.Text.ToLower() == "sql")
    //                    {
    //                        dtype = getSqlDataType(dr["grand_total_field"].ToString(), hsDt);
    //                        if (dr["grand_total_field"].ToString().IndexOf("].[") == -1)
    //                            caption = dr["grand_total_field"].ToString();
    //                        else
    //                            caption = dr["grand_total_field"].ToString().Substring(dr["grand_total_field"].ToString().IndexOf("].[") + 3).TrimEnd(']');
    //                        //xInnerChild.InnerText = "[" + caption + "]";

    //                        if (dtype.ToLower() == "double")
    //                            formula = "\"" + currency + " \"+" + " Sum([" + caption + "])";//caption setCaption(lblReportSrc.Text, dr["subtotal_field"].ToString(), "")
    //                        else if (dtype.ToLower() == "decimal")
    //                            formula = "Format(Sum([" + caption + "])," + "\"0.00\")";//caption
    //                        else
    //                            formula = "Sum([" + caption + "])";//caption

    //                        //if (dr["grand_total_field"].ToString().IndexOf("].[") == -1)
    //                        //    formula = "Format(Sum(" + caption + ")," + "\"0.00\")"; //dr["grand_total_field"].ToString()
    //                        //else
    //                        //    formula = "Format(Sum(" + caption + ")," + "\"0.00\")";//dr["grand_total_field"].ToString().Substring(dr["grand_total_field"].ToString().IndexOf("].[") + 3).TrimEnd(']')
    //                    }
    //                    xInnerChild.InnerText = formula;
    //                    xChild.AppendChild(xInnerChild);
    //                    formula = "";

    //                    xInnerChild = xDoc.CreateElement("Left");
    //                    xInnerChild.InnerText = hsRptLocations[dr["grand_total_field"].ToString()].ToString();
    //                    xChild.AppendChild(xInnerChild);
    //                    xInnerChild = xDoc.CreateElement("Calculated");
    //                    xInnerChild.InnerText = "true";
    //                    xChild.AppendChild(xInnerChild);
    //                    xInnerChild = xDoc.CreateElement("Width");
    //                    if (lblReportSrc.Text.ToLower() == "sql")
    //                    {
    //                        if (dr["grand_total_field"].ToString().IndexOf("].[") == -1)
    //                            xInnerChild.InnerText = hsReportWidth[dr["grand_total_field"].ToString()].ToString();
    //                        else
    //                            xInnerChild.InnerText = hsReportWidth[dr["grand_total_field"].ToString().Substring(dr["grand_total_field"].ToString().IndexOf("].[") + 3).TrimEnd(']')].ToString();
    //                    }
    //                    else
    //                        xInnerChild.InnerText = hsReportWidth[dr["grand_total_field"].ToString()].ToString();

    //                    //xInnerChild.InnerText = hsReportWidth[dr["grand_total_field"].ToString()].ToString(); //"1000";
    //                    xChild.AppendChild(xInnerChild);
    //                    xInnerChild = xDoc.CreateElement("Height");
    //                    xInnerChild.InnerText = "300";
    //                    xChild.AppendChild(xInnerChild);
    //                    xInnerChild = xDoc.CreateElement("Align");
    //                    xInnerChild.InnerText = "8";
    //                    xChild.AppendChild(xInnerChild);

    //                    //Font
    //                    xInnerChild = xDoc.CreateElement("Font");
    //                    xNode = xDoc.CreateElement("Bold");
    //                    xNode.InnerText = "true";
    //                    xInnerChild.AppendChild(xNode);
    //                    xNode = xDoc.CreateElement("Name");
    //                    xNode.InnerText = "Arial";
    //                    xInnerChild.AppendChild(xNode);
    //                    xNode = xDoc.CreateElement("Size");
    //                    xNode.InnerText = "8";
    //                    xInnerChild.AppendChild(xNode);
    //                    xChild.AppendChild(xInnerChild);
    //                    xParent.AppendChild(xChild);
    //                    idx++;
    //                }
    //            }
    //        }
    //        dtG = null;
    //        #endregion
            
    //        #region Header Text
    //        if (txtHeaderText.Text.Trim() != "")
    //        {
    //            xChild = xDoc.CreateElement("Field");
    //            xInnerChild = xDoc.CreateElement("Name");
    //            xInnerChild.InnerText = "lblHdrField";
    //            xChild.AppendChild(xInnerChild);
    //            xInnerChild = xDoc.CreateElement("Section");
    //            xInnerChild.InnerText = "1";
    //            xChild.AppendChild(xInnerChild);
    //            xInnerChild = xDoc.CreateElement("Text");
    //            xInnerChild.InnerText = txtHeaderText.Text;
    //            xChild.AppendChild(xInnerChild);
    //            xInnerChild = xDoc.CreateElement("Width");
    //            xInnerChild.InnerText = getLength(txtHeaderText.Text).ToString();
    //            xChild.AppendChild(xInnerChild);
    //            xInnerChild = xDoc.CreateElement("Height");
    //            xInnerChild.InnerText = "300";
    //            xChild.AppendChild(xInnerChild);
    //            xInnerChild = xDoc.CreateElement("Left");
    //            xInnerChild.InnerText = "10";
    //            xChild.AppendChild(xInnerChild);
    //            xInnerChild = xDoc.CreateElement("Top");
    //            xInnerChild.InnerText = "1050";
    //            xChild.AppendChild(xInnerChild);

    //            //Font
    //            xInnerChild = xDoc.CreateElement("Font");
    //            xNode = xDoc.CreateElement("Bold");
    //            xNode.InnerText = "-1";
    //            xInnerChild.AppendChild(xNode);
    //            xNode = xDoc.CreateElement("Name");
    //            xNode.InnerText = "Arial";
    //            xInnerChild.AppendChild(xNode);
    //            xNode = xDoc.CreateElement("Size");
    //            xNode.InnerText = "10";
    //            xInnerChild.AppendChild(xNode);

    //            xChild.AppendChild(xInnerChild);
    //            xParent.AppendChild(xChild);
    //        }
            
    //        #endregion

    //        #region Footer Text
    //        if (txtFooterText.Text.Trim() != "")
    //        {
    //            xChild = xDoc.CreateElement("Field");
    //            xInnerChild = xDoc.CreateElement("Name");
    //            xInnerChild.InnerText = "lblFooField";
    //            xChild.AppendChild(xInnerChild);
    //            xInnerChild = xDoc.CreateElement("Section");
    //            xInnerChild.InnerText = "4";
    //            xChild.AppendChild(xInnerChild);
    //            xInnerChild = xDoc.CreateElement("Text");
    //            xInnerChild.InnerText = txtFooterText.Text;
    //            xChild.AppendChild(xInnerChild);
    //            xInnerChild = xDoc.CreateElement("Width");
    //            xInnerChild.InnerText = getLength(txtFooterText.Text).ToString();
    //            xChild.AppendChild(xInnerChild);
    //            xInnerChild = xDoc.CreateElement("Height");
    //            xInnerChild.InnerText = "300";
    //            xChild.AppendChild(xInnerChild);
    //            xInnerChild = xDoc.CreateElement("Left");
    //            xInnerChild.InnerText = "10";
    //            xChild.AppendChild(xInnerChild);
    //            xParent.AppendChild(xChild);
    //        }
    //        #endregion

    //        #region Display Date
    //        if (chkDisplayDate.Checked == true)
    //        {
    //            xChild = xDoc.CreateElement("Field");
    //            xInnerChild = xDoc.CreateElement("Name");
    //            xInnerChild.InnerText = "lblDateField";
    //            xChild.AppendChild(xInnerChild);
    //            xInnerChild = xDoc.CreateElement("Section");
    //            xInnerChild.InnerText = "4";
    //            xChild.AppendChild(xInnerChild);
    //            xInnerChild = xDoc.CreateElement("Text");
    //            xInnerChild.InnerText = DateTime.Now.ToShortDateString();
    //            xChild.AppendChild(xInnerChild);
    //            xInnerChild = xDoc.CreateElement("Width");
    //            xInnerChild.InnerText = "1100";
    //            xChild.AppendChild(xInnerChild);
    //            xInnerChild = xDoc.CreateElement("Height");
    //            xInnerChild.InnerText = "300";
    //            xChild.AppendChild(xInnerChild);
    //            xInnerChild = xDoc.CreateElement("Left");
    //            xInnerChild.InnerText = (reportWidth - 1100).ToString();
    //            xChild.AppendChild(xInnerChild);
    //            xParent.AppendChild(xChild);
    //        }
    //        #endregion

    //        #region Display Page Number
    //        if (chkDisplayPageNum.Checked == true)
    //        {
    //            xChild = xDoc.CreateElement("Field");
    //            xInnerChild = xDoc.CreateElement("Name");
    //            xInnerChild.InnerText = "lblPageNoField";
    //            xChild.AppendChild(xInnerChild);
    //            xInnerChild = xDoc.CreateElement("Section");
    //            xInnerChild.InnerText = "4";
    //            xChild.AppendChild(xInnerChild);
    //            xInnerChild = xDoc.CreateElement("Text");
    //            xInnerChild.InnerText = "\"Page\"" + " & [Page] &  " + "\" of \"" + " & [Pages]";
    //            xChild.AppendChild(xInnerChild);
    //            xInnerChild = xDoc.CreateElement("Width");
    //            xInnerChild.InnerText = "3360";
    //            xChild.AppendChild(xInnerChild);
    //            xInnerChild = xDoc.CreateElement("Height");
    //            xInnerChild.InnerText = "300";
    //            xChild.AppendChild(xInnerChild);
    //            xInnerChild = xDoc.CreateElement("Left");
    //            xInnerChild.InnerText = ((reportWidth / 2) - (1680)).ToString();
    //            xChild.AppendChild(xInnerChild);
    //            xInnerChild = xDoc.CreateElement("Calculated");
    //            xInnerChild.InnerText = "true";
    //            xChild.AppendChild(xInnerChild);
    //            xInnerChild = xDoc.CreateElement("Align");
    //            xInnerChild.InnerText = "7";
    //            xChild.AppendChild(xInnerChild);
    //            xParent.AppendChild(xChild);
    //        }
    //        #endregion

    //        reportNode.AppendChild(xParent);
    //        xDoc.DocumentElement.AppendChild(reportNode);
    //        hsRptLocations = null;
    //        hsDupFields = null;

    //        //xDoc.Save(Server.MapPath(".") + "\\report\\reportxml.xml");
    //        string fileName = "";
    //        if (txtRepName.Text.Trim() == "")
    //        {
    //            fileName = "NewReport";
    //            reportViewer.Report.Load(xDoc, "New Report");
    //        }
    //        else
    //        {
    //            fileName = txtRepName.Text;
    //            reportViewer.Report.Load(xDoc, txtRepName.Text);
    //        }

    //        //DataTable resDt = hdd.GetDataTable(sql);
    //        //reportViewer.Report.DataSource.Recordset = resDt;

    //        #region Export section
    //        if (exportFlag)
    //        {
    //            MemoryStream memStream = new MemoryStream();
    //            Response.ClearContent();
    //            Response.ClearHeaders();
    //            switch (exportFormat.ToUpper().Trim())
    //            { 
    //                case "XLS":
    //                    reportViewer.Report.RenderToStream(memStream, C1.C1Report.FileFormatEnum.Excel);
    //                    Response.ContentType = "application/xls";
    //                    fileName += ".xls";
    //                    break;
    //                case "PDF":
    //                    reportViewer.Report.RenderToStream(memStream, C1.C1Report.FileFormatEnum.PDF);
    //                    Response.ContentType = "application/pdf";
    //                    fileName += ".pdf";
    //                    break;
    //                case "RTF":
    //                    reportViewer.Report.RenderToStream(memStream, C1.C1Report.FileFormatEnum.RTF);
    //                    Response.ContentType = "application/rtf";
    //                    fileName += ".rtf";
    //                    break;
    //                case "HTML":
    //                    reportViewer.Report.RenderToStream(memStream, C1.C1Report.FileFormatEnum.HTMLPaged);
    //                    Response.ContentType = "application/htm";
    //                    fileName += ".htm";
    //                    break;
    //                default:
    //                    reportViewer.Report.RenderToStream(memStream, C1.C1Report.FileFormatEnum.Excel);
    //                    Response.ContentType = "application/xls";
    //                    fileName += ".xls";
    //                    break;
    //            }                
    //            byte[] bArray = memStream.ToArray();                
    //            Response.AddHeader("content-disposition", "attachment;filename=\"" + fileName + "\"");
    //            Response.BinaryWrite(bArray);
    //            bArray = null;
    //            memStream.Close();
    //            memStream.Flush();
    //            memStream = null;
    //        }
    //        #endregion

    //        if (Session["xdoc"] == null)
    //            Session.Add("xdoc", xDoc);
    //        hsFieldNames = null;
    //        xDoc = null;
    //    }
    //    catch (Exception ex)
    //    {
    //        LogWriter.WriteLog("generateReport : Error: " + ex.Message);
    //    }
    //    finally
    //    {
    //        xDoc = null;
    //    }
    //    return isGenerated;
    //}

    private DataTable getReportData(string sqlQry)
    {
        DataTable retDt = new DataTable();
        try        
        {
            
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("generateReport : Error: " + ex.Message);
        }
        return retDt;
    }


    /// <summary>
    /// function generated report in XML file. The XML file is linked with report component.
    /// </summary>
    /// <param name="dsR">DataSet</param>
    /// <returns>true/false</returns>
    private bool generateReportXML(DataSet dsR)
    {
        bool isGenerated = true;
        XmlTextWriter xWriter = null;
        int reportWidth = 10;
        
        try
        {
            //reportViewer.PrintSection += new C1.C1Report.ReportEventHandler(reportViewer_PrintSection);
            //reportViewer.Paged = true;

            if (!Directory.Exists(Server.MapPath(".") + "\\report"))
                Directory.CreateDirectory(Server.MapPath(".") + "\\report");

            if (File.Exists(Server.MapPath(".") + "\\report\\" + hf_af_row_id1.Value + ".xml"))
                File.Delete(Server.MapPath(".") + "\\report\\" + hf_af_row_id1.Value + ".xml");

            xWriter = new XmlTextWriter(Server.MapPath(".") + "\\report\\" + hf_af_row_id1.Value + ".xml", Encoding.Default);

            xWriter.WriteStartDocument(); //writing XML version
            xWriter.WriteStartElement("Reports");
            xWriter.WriteStartElement("Report");

             #region Report Information
            DataTable dt = dsR.Tables["p_sy_report"];
            if (dt.Rows.Count == 0)
            {
                xWriter.WriteStartElement("Name");
                xWriter.WriteString("New Report");
                xWriter.WriteEndElement();
                xWriter.WriteStartElement("ReportInfo");
                xWriter.WriteStartElement("Title");
                xWriter.WriteString("NOT SPECIFIED");
                xWriter.WriteEndElement();//Title
                xWriter.WriteEndElement();//ReportInfo
            }
            else
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    xWriter.WriteStartElement("Name");
                    if (dt.Rows[i]["rpt_name"].ToString().Trim() == "")
                        xWriter.WriteString("New Report");
                    else
                        xWriter.WriteString(dt.Rows[i]["rpt_name"].ToString());
                    xWriter.WriteEndElement();
                    xWriter.WriteStartElement("ReportInfo");
                    xWriter.WriteStartElement("Title");
                    if (txtRepTitle.Text.Trim() == "")
                        xWriter.WriteString("NOT SPECIFIED");
                    else
                        xWriter.WriteString(HttpUtility.HtmlEncode(txtRepTitle.Text));
                    xWriter.WriteEndElement();//Title
                    xWriter.WriteEndElement();//ReportInfo
                }
            }
            #endregion

            #region Assigning DataSource - object or query
            if (Session["dbcon"] == null)
            {
                LogWriter.WriteLog("generateReportXML : Error : connection string is empty");
                return false;
            }

            DataTable dtTmp = null;
            string sql = "", cols = "", tabName = "";

            if (lblReportSrc.Text.ToLower() == "object")
            {
                dtTmp = hdd.GetDataTable("select [object_name]obj_name, object_table from sy_obj where [object_id]=(select [object_id] from sy_report_obj where rpt_id='" + hf_af_row_id1.Value + "')");
                if (dtTmp == null)
                {
                    LogWriter.WriteLog("generateReportXML : Error : Table/Query object is empty");
                    return false;
                }

                if (dtTmp.Rows.Count > 0)
                    tabName = dtTmp.Rows[0]["object_table"].ToString();
                else
                {
                    dtTmp = hdd.GetDataTable("select [object_name]obj_name, object_table from sy_obj where [object_id]='" + cmbObjects.SelectedValue.Substring(cmbObjects.SelectedValue.IndexOf("@") + 1) + "'");
                    if (dtTmp.Rows.Count > 0)
                        tabName = dtTmp.Rows[0]["object_table"].ToString();
                }
            }
            else if (lblReportSrc.Text.ToLower() == "sql")
            {
                dtTmp = hdd.GetDataTable("select report_base_sql from sy_report_sql where report_base_id=(select object_id from sy_report_obj where rpt_id='" + hf_af_row_id1.Value + "')");
                if (dtTmp == null)
                {
                    LogWriter.WriteLog("generateReportXML : Error : Table/Query object is empty");
                    return false;
                }
                if (dtTmp.Rows.Count == 0)
                {
                    dtTmp = hdd.GetDataTable("select report_base_sql from sy_report_sql where report_base_id='" + cmbObjects.SelectedValue.Substring(cmbObjects.SelectedValue.IndexOf("@") + 1) + "'");
                    if (dtTmp.Rows.Count > 0)
                        sql = dtTmp.Rows[0]["report_base_sql"].ToString();
                    else
                    {
                        LogWriter.WriteLog("generateReportXML : Error : Table/Query object is empty");
                        return false;
                    }
                }
                else
                    sql = dtTmp.Rows[0]["report_base_sql"].ToString();
            }
            dtTmp = null;

            dt = dsR.Tables["p_sy_report_att"];
            if (dt != null)
            {
                if (dt.Rows.Count == 0)
                {
                    dsR = collect_step_values(1);
                    dt = dsR.Tables["p_sy_report_att"];
                }

                if (lblReportSrc.Text.ToLower() == "object")
                {
                    foreach (DataRow dr in dt.Rows)
                    {
                        string caption = setCaption(lblReportSrc.Text, dr["attrib_id"].ToString(), dr["caption"].ToString());
                        if (dr["attrib_id"].ToString().IndexOf("].[") == -1)
                        {
                            cols += "[" + getAttribId(lblReportSrc.Text, dr["attrib_id"].ToString()) + "] as [" + caption + "],";
                        }
                        else
                        {
                            string attrib_id = getAttribId(lblReportSrc.Text, dr["attrib_id"].ToString().Substring(dr["attrib_id"].ToString().IndexOf("].[") + 3).TrimEnd(']'));

                            if (attrib_id.ToLower() == "created_by" || attrib_id.ToLower() == "modified_by" || attrib_id.ToLower() == "owner_id")
                            {
                                string objName = dr["attrib_id"].ToString().Substring(0, dr["attrib_id"].ToString().IndexOf("]")).Replace("[", "").Replace("]", "");
                                cols += "(" + getOwnerName(attrib_id, objName) + ") as [" + caption + "],";
                            }
                            else
                                cols += "[" + attrib_id + "] as [" + caption + "],";
                        }
                        caption = "";
                    }
                    sql = "select " + cols.TrimEnd(',') + " from " + tabName;
                }
            }
            else
            {
                if (lblReportSrc.Text.ToLower() == "object")
                {
                    foreach (ListItem li in lstSelectedFields1.Items)
                    {
                        string caption = setCaption(lblReportSrc.Text, li.Value.ToString(), "");
                        if (li.Value.IndexOf("].[") == -1)
                            cols += "[" + getAttribId(lblReportSrc.Text, li.Value) + "] as [" + li.Text + "],";
                        else
                            cols += "[" + getAttribId(lblReportSrc.Text, li.Value.Substring(li.Value.IndexOf("].[") + 3).TrimEnd(']')) + "] as [" + caption + "],";
                        caption = "";
                    }
                    sql = "select " + cols.TrimEnd(',') + " from " + tabName;
                }

                createDataTable(1, ref dsR);
                dt = dsR.Tables["p_sy_report_att"];
                fillSelectedValues(ref dt);
            }

            xWriter.WriteStartElement("DataSource");
            xWriter.WriteStartElement("ConnectionString");
            xWriter.WriteString(makeOLEDBConnectionString(Session["dbcon"].ToString()));
            xWriter.WriteEndElement();//ConnectionString
            xWriter.WriteStartElement("RecordSource");
            xWriter.WriteString(sql);
            xWriter.WriteEndElement();//RecordSource
            xWriter.WriteEndElement();//DataSource
            #endregion

            #region Layout information
            //Calculating width
            for (int i = 0; i < dt.Rows.Count; i++)
                reportWidth += 1500;

            xWriter.WriteStartElement("Layout");
            xWriter.WriteStartElement("Width");
            xWriter.WriteString(reportWidth.ToString());
            xWriter.WriteEndElement();//Width
            xWriter.WriteStartElement("Orientation");
            xWriter.WriteString("2");//Lanscape
            xWriter.WriteEndElement();//Orientation
            xWriter.WriteStartElement("PaperSize");
            xWriter.WriteString("5");//Legal
            xWriter.WriteEndElement();//PaperSize
            xWriter.WriteEndElement();//Layout

            xWriter.WriteStartElement("Font");
            xWriter.WriteStartElement("Name");
            xWriter.WriteString("Arial");
            xWriter.WriteEndElement();//Name
            xWriter.WriteStartElement("Size");
            xWriter.WriteString("10");
            xWriter.WriteEndElement();//Size
            xWriter.WriteEndElement();//Font

            xWriter.WriteStartElement("OnOpen");
            xWriter.WriteString("' -- style script start " + Convert.ToChar(13) + Convert.ToChar(10) + "_styleCtr = 0 " + Convert.ToChar(13) + Convert.ToChar(10) + "' -- style script end");
            xWriter.WriteEndElement();//OnOpen
            #endregion

            #region Grouping Sections
            xWriter.WriteStartElement("Groups");

            DataTable dtG = dsR.Tables["p_report_grouping"];
            if (dtG == null)
                dtG = new DataTable();
            for (int i = 0; i < dtG.Rows.Count; i++)
            {
                DataRow dr = dtG.Rows[i];
                xWriter.WriteStartElement("Group");
                xWriter.WriteStartElement("Name");
                xWriter.WriteString("Group" + (i + 1).ToString());
                xWriter.WriteEndElement();//Name
                //Group by
                xWriter.WriteStartElement("GroupBy");
                string caption = "";
                if (lblReportSrc.Text.ToLower() == "object")
                    caption = "[" + setCaption(lblReportSrc.Text, dr["grouping_field"].ToString(), "") + "]";
                else if (lblReportSrc.Text.ToLower() == "sql")
                {
                    if (dr["grouping_field"].ToString().IndexOf("].[") == -1)
                        caption = dr["grouping_field"].ToString();
                    else
                        caption = dr["grouping_field"].ToString().Substring(dr["grouping_field"].ToString().IndexOf("].[") + 3).TrimEnd(']');
                }
                xWriter.WriteString(caption);
                xWriter.WriteEndElement();//GroupBy
                xWriter.WriteStartElement("Sort");
                xWriter.WriteString(dr["grouping_order"].ToString().ToLower() == "ascending" ? "1" : "2");
                xWriter.WriteEndElement();//Sort
                xWriter.WriteEndElement();//Group
                dr = null;
            }
            dtG = null;

            xWriter.WriteEndElement();//Groups
            #endregion

            #region Sections
            //Detail section
            xWriter.WriteStartElement("Sections");
            xWriter.WriteStartElement("Section");
            xWriter.WriteStartElement("Name");
            xWriter.WriteString("Detail");
            xWriter.WriteEndElement();//Name
            xWriter.WriteStartElement("Type");
            xWriter.WriteString("0");
            xWriter.WriteEndElement();//Type
            xWriter.WriteStartElement("Height");
            xWriter.WriteString("300");
            xWriter.WriteEndElement();//Sections
            xWriter.WriteStartElement("OnPrint");
            xWriter.WriteString("' -- style script start " + Convert.ToChar(13) + Convert.ToChar(10) + " detail.BackColor = iif(_styleCtr mod 2 = 0, rgb(191,219,255),rgb(228,240,255)) " + Convert.ToChar(13) + Convert.ToChar(10) + "_styleCtr = _styleCtr + 1 " + Convert.ToChar(13) + Convert.ToChar(10) + "' -- style script end");
            xWriter.WriteEndElement();//Sections
            xWriter.WriteEndElement();//Section

            //Header section
            xWriter.WriteStartElement("Section");
            xWriter.WriteStartElement("Name");
            xWriter.WriteString("Header");
            xWriter.WriteEndElement();//Name
            xWriter.WriteStartElement("Type");
            xWriter.WriteString("1");
            xWriter.WriteEndElement();//Type
            xWriter.WriteStartElement("Height");
            xWriter.WriteString("500");
            xWriter.WriteEndElement();//Height
            xWriter.WriteEndElement();//Section

            //Footer
            xWriter.WriteStartElement("Section");
            xWriter.WriteStartElement("Name");
            xWriter.WriteString("Footer");
            xWriter.WriteEndElement();//Name
            xWriter.WriteStartElement("Type");
            xWriter.WriteString("2");
            xWriter.WriteEndElement();//Type
            xWriter.WriteStartElement("Height");
            xWriter.WriteString("300");
            xWriter.WriteEndElement();//Height
            xWriter.WriteEndElement();//Section

            //Page Header
            xWriter.WriteStartElement("Section");
            xWriter.WriteStartElement("Name");
            xWriter.WriteString("PageHeader");
            xWriter.WriteEndElement();//Name
            xWriter.WriteStartElement("Type");
            xWriter.WriteString("3");
            xWriter.WriteEndElement();//Type
            xWriter.WriteStartElement("Height");
            xWriter.WriteString("300");
            xWriter.WriteEndElement();//Height
            xWriter.WriteStartElement("BackColor");
            xWriter.WriteString("16431752");
            xWriter.WriteEndElement();//BackColor
            xWriter.WriteEndElement();//Section

            //PageFooter
            xWriter.WriteStartElement("Section");
            xWriter.WriteStartElement("Name");
            xWriter.WriteString("PageFooter");
            xWriter.WriteEndElement();//Name
            xWriter.WriteStartElement("Type");
            xWriter.WriteString("4");
            xWriter.WriteEndElement();//Type
            xWriter.WriteStartElement("Height");
            xWriter.WriteString("300");
            xWriter.WriteEndElement();//Height
            //xWriter.WriteStartElement("BackColor");
            //xWriter.WriteString("16431752");
            //xWriter.WriteEndElement();//BackColor
            xWriter.WriteEndElement();//Section

            //Grouping Header/Footer Sections
            DataTable dtS = dsR.Tables["p_report_grouping"];
            int sec = 5;
            if (dtS == null)
                dtS = new DataTable();
            for (int k = 0; k < dtS.Rows.Count; k++)
            {
                DataRow dr = dt.Rows[k];
                //Group Header 
                xWriter.WriteStartElement("Section");
                xWriter.WriteStartElement("Name");
                xWriter.WriteString("Group" + (k + 1).ToString() + "_Header");
                xWriter.WriteEndElement();//Name
                xWriter.WriteStartElement("Type");
                xWriter.WriteString(sec.ToString());
                xWriter.WriteEndElement();//Type
                xWriter.WriteStartElement("Height");
                xWriter.WriteString("300");
                xWriter.WriteEndElement();//Height
                xWriter.WriteEndElement();//Section

                sec++;

                //Group Footer
                xWriter.WriteStartElement("Section");
                xWriter.WriteStartElement("Name");
                xWriter.WriteString("Group" + (k + 1).ToString() + "_Footer");
                xWriter.WriteEndElement();//Name
                xWriter.WriteStartElement("Type");
                xWriter.WriteString(sec.ToString());
                xWriter.WriteEndElement();//Type
                xWriter.WriteStartElement("Height");
                xWriter.WriteString("300");
                xWriter.WriteEndElement();//Height
                xWriter.WriteEndElement();//Section

                sec++;
            }

            xWriter.WriteEndElement();//Sections
            #endregion

            #region Report Header - Title

            xWriter.WriteStartElement("Fields");
            xWriter.WriteStartElement("Field");
            xWriter.WriteStartElement("Name");
            xWriter.WriteString("title");
            xWriter.WriteEndElement();//title
            xWriter.WriteStartElement("Section");
            xWriter.WriteString("1");
            xWriter.WriteEndElement();//Section
            xWriter.WriteStartElement("Text");
            xWriter.WriteString(txtRepTitle.Text.Trim() == "" ? cmbObjects.SelectedItem.Text : HttpUtility.HtmlEncode(txtRepTitle.Text)); //"Untitled Report"
            xWriter.WriteEndElement();//Text
            xWriter.WriteStartElement("Height");
            xWriter.WriteString("400");
            xWriter.WriteEndElement();//Height
            xWriter.WriteStartElement("Width");
            xWriter.WriteString("9270");
            xWriter.WriteEndElement();//Width
            xWriter.WriteStartElement("Align");
            xWriter.WriteString("7");
            xWriter.WriteEndElement();//Align
            xWriter.WriteStartElement("ForeColor");
            xWriter.WriteString("16711680");
            xWriter.WriteEndElement();//ForeColor
            //Font
            xWriter.WriteStartElement("Font");
            xWriter.WriteStartElement("Bold");
            xWriter.WriteString("-1");
            xWriter.WriteEndElement();//Bold
            xWriter.WriteStartElement("Name");
            xWriter.WriteString("Arial");
            xWriter.WriteEndElement();//Name
            xWriter.WriteStartElement("Size");
            xWriter.WriteString("12");
            xWriter.WriteEndElement();//Size
            xWriter.WriteEndElement();//Font
            xWriter.WriteEndElement();//Field           
            #endregion

            #region Report Labels/Captions
            int left = 50;
            int idx = 1;

            foreach (DataRow dr in dt.Rows)
            {
                xWriter.WriteStartElement("Field");
                xWriter.WriteStartElement("Name");
                xWriter.WriteString("lbl" + idx.ToString());
                xWriter.WriteEndElement();//Name
                xWriter.WriteStartElement("Section");
                xWriter.WriteString("3");
                xWriter.WriteEndElement();//Section
                xWriter.WriteStartElement("Text");

                string caption = setCaption(lblReportSrc.Text, dr["attrib_id"].ToString(), dr["caption"].ToString());
                xWriter.WriteString(caption);
                caption = "";

                xWriter.WriteEndElement();//Text
                xWriter.WriteStartElement("Left");
                xWriter.WriteString(left.ToString());
                xWriter.WriteEndElement();//Left
                xWriter.WriteStartElement("Width");
                xWriter.WriteString("1000");
                xWriter.WriteEndElement();//Width
                xWriter.WriteStartElement("CanGrow");
                xWriter.WriteString("-1");
                xWriter.WriteEndElement();//CanGrow
                xWriter.WriteStartElement("Height");
                xWriter.WriteString("300");
                xWriter.WriteEndElement();//Height
                xWriter.WriteStartElement("ForeColor");
                xWriter.WriteString("16777215");
                xWriter.WriteEndElement();//ForeColor

                //Wordwrap
                xWriter.WriteStartElement("WordWrap");

                if (dr["is_wrap"].ToString().ToLower() == "yes" || dr["is_wrap"].ToString().ToLower() == "no")
                    xWriter.WriteString(dr["is_wrap"].ToString() == "Yes" ? "true" : "No");
                else
                {
                    if (Convert.ToBoolean(dr["is_wrap"].ToString()) == true)
                        xWriter.WriteString("true");
                    else
                        xWriter.WriteString("false");
                }
                xWriter.WriteEndElement();//WordWrap

                //Font
                xWriter.WriteStartElement("Font");
                xWriter.WriteStartElement("Bold");
                if (dr["is_bold"].ToString().ToLower() == "yes" || dr["is_bold"].ToString().ToLower() == "no")
                    xWriter.WriteString(dr["is_bold"].ToString() == "Yes" ? "true" : "No");
                else
                {
                    if (Convert.ToBoolean(dr["is_bold"].ToString()) == true)
                        xWriter.WriteString("true");
                    else
                        xWriter.WriteString("false");
                }
                xWriter.WriteEndElement();//Bold
                xWriter.WriteStartElement("Name");
                xWriter.WriteString("Arial");
                xWriter.WriteEndElement();//Name
                xWriter.WriteStartElement("Size");
                xWriter.WriteString("10");
                xWriter.WriteEndElement();//Size
                xWriter.WriteEndElement();//Font

                xWriter.WriteEndElement();//Field   
                left += 1500;
                idx++;
            }
            #endregion

            #region Report Fields/Values
            left = 50;
            idx = 1;
            Hashtable hsRptLocations = new Hashtable();
            foreach (DataRow dr in dt.Rows)
            {
                xWriter.WriteStartElement("Field");
                xWriter.WriteStartElement("Name");
                xWriter.WriteString("Field" + idx.ToString());
                xWriter.WriteEndElement();//Name
                xWriter.WriteStartElement("Section");
                xWriter.WriteString("0");
                xWriter.WriteEndElement();//Section
                xWriter.WriteStartElement("Text");

                string caption = "";
                if (lblReportSrc.Text.ToLower() == "object")
                    caption = "[" + setCaption(lblReportSrc.Text, dr["attrib_id"].ToString(), dr["caption"].ToString()) + "]";
                else if (lblReportSrc.Text.ToLower() == "sql")
                {
                    if (dr["attrib_id"].ToString().IndexOf("].[") == -1)
                        caption = dr["attrib_id"].ToString();
                    else
                        caption = dr["attrib_id"].ToString().Substring(dr["attrib_id"].ToString().IndexOf("].[") + 3).TrimEnd(']');
                }
                xWriter.WriteString(caption);
                caption = "";

                xWriter.WriteEndElement();//Text
                xWriter.WriteStartElement("Left");
                xWriter.WriteString(left.ToString());
                xWriter.WriteEndElement();//Left
                hsRptLocations.Add(dr["attrib_id"], left);
                xWriter.WriteStartElement("Calculated");
                xWriter.WriteString("true");
                xWriter.WriteEndElement();//Calculated
                xWriter.WriteStartElement("Width");
                xWriter.WriteString("1000");
                xWriter.WriteEndElement();//Width
                //Wordwrap
                xWriter.WriteStartElement("WordWrap");

                if (dr["is_wrap"].ToString().ToLower() == "yes" || dr["is_wrap"].ToString().ToLower() == "no")
                    xWriter.WriteString(dr["is_wrap"].ToString() == "Yes" ? "true" : "No");
                else
                {
                    if (Convert.ToBoolean(dr["is_wrap"].ToString()) == true)
                        xWriter.WriteString("true");
                    else
                        xWriter.WriteString("false");
                }
                xWriter.WriteEndElement();//WordWrap

                xWriter.WriteStartElement("CanGrow");
                xWriter.WriteString("-1");
                xWriter.WriteEndElement();//CanGrow
                xWriter.WriteStartElement("Height");
                xWriter.WriteString("300");
                xWriter.WriteEndElement();//Height

                //Font
                xWriter.WriteStartElement("Font");
                //Bold
                xWriter.WriteStartElement("Bold");
                if (dr["is_bold"].ToString().ToLower() == "yes" || dr["is_bold"].ToString().ToLower() == "no")
                    xWriter.WriteString(dr["is_bold"].ToString() == "Yes" ? "true" : "No");
                else
                {
                    if (Convert.ToBoolean(dr["is_bold"].ToString()) == true)
                        xWriter.WriteString("true");
                    else
                        xWriter.WriteString("false");
                }

                xWriter.WriteEndElement();//Bold
                xWriter.WriteStartElement("Name");
                xWriter.WriteString("Arial");
                xWriter.WriteEndElement();//Name
                xWriter.WriteStartElement("Size");
                xWriter.WriteString("8");
                xWriter.WriteEndElement();//Size
                xWriter.WriteEndElement();//Font

                xWriter.WriteEndElement();//Field   

                left += 1500;
                idx++;
            }
            dt = null;
            #endregion

            #region Report Grouping Header
            left = 50;
            //Header
            dtG = dsR.Tables["p_report_grouping_header"];
            if (dtG == null)
                dtG = new DataTable();
            foreach (DataRow dr in dtG.Rows)
            {
                //Header Label
                xWriter.WriteStartElement("Field");
                xWriter.WriteStartElement("Name");
                xWriter.WriteString("Field" + idx.ToString());
                xWriter.WriteEndElement();//Name
                xWriter.WriteStartElement("Section");
                if (dr["group_sequence"].ToString() == "1")
                    xWriter.WriteString("5");
                else if (dr["group_sequence"].ToString() == "2")
                    xWriter.WriteString("7");
                else if (dr["group_sequence"].ToString() == "3")
                    xWriter.WriteString("9");
                xWriter.WriteEndElement();//Section
                xWriter.WriteStartElement("Text");
                string caption = "";
                if (lblReportSrc.Text.ToLower() == "object")
                    caption = setCaption(lblReportSrc.Text, dr["header_field"].ToString(), "");
                else if (lblReportSrc.Text.ToLower() == "sql")
                {
                    if (dr["header_field"].ToString().IndexOf("].[") == -1)
                        caption = dr["header_field"].ToString();
                    else
                    {
                            caption = dr["header_field"].ToString().Substring(dr["header_field"].ToString().IndexOf("].[") + 3).TrimEnd(']');
                    }
                }
                xWriter.WriteString(caption);
                caption = "";

                xWriter.WriteEndElement();//Text
                xWriter.WriteStartElement("Left");
                xWriter.WriteString(left.ToString());
                xWriter.WriteEndElement();//Left
                xWriter.WriteStartElement("Calculated");
                xWriter.WriteString("false");
                xWriter.WriteEndElement();//Calculated
                xWriter.WriteStartElement("Width");
                xWriter.WriteString("1000");
                xWriter.WriteEndElement();//Width
                xWriter.WriteStartElement("Height");
                xWriter.WriteString("300");
                xWriter.WriteEndElement();//Height
                //Font
                xWriter.WriteStartElement("Font");
                xWriter.WriteStartElement("Bold");
                xWriter.WriteString("true");
                xWriter.WriteEndElement();//Bold
                xWriter.WriteStartElement("Name");
                xWriter.WriteString("Arial");
                xWriter.WriteEndElement();//Name
                xWriter.WriteStartElement("Size");
                xWriter.WriteString("8");
                xWriter.WriteEndElement();//Size
                xWriter.WriteStartElement("WordWrap");
                xWriter.WriteString("-1");
                xWriter.WriteEndElement();//WordWrap
                xWriter.WriteEndElement();//Font
                xWriter.WriteEndElement();//Field   

                left += 1200;
                idx++;

                //Header Field
                xWriter.WriteStartElement("Field");
                xWriter.WriteStartElement("Name");
                xWriter.WriteString("Field" + idx.ToString());
                xWriter.WriteEndElement();//Name
                xWriter.WriteStartElement("Section");
                if (dr["group_sequence"].ToString() == "1")
                    xWriter.WriteString("5");
                else if (dr["group_sequence"].ToString() == "2")
                    xWriter.WriteString("7");
                else if (dr["group_sequence"].ToString() == "3")
                    xWriter.WriteString("9");
                xWriter.WriteEndElement();//Section
                xWriter.WriteStartElement("Text");
                caption = "";
                if (lblReportSrc.Text.ToLower() == "object")
                    caption = "[" + setCaption(lblReportSrc.Text, dr["header_field"].ToString(), "") + "]";
                else if (lblReportSrc.Text.ToLower() == "sql")
                {
                    if (dr["header_field"].ToString().IndexOf("].[") == -1)
                        caption = dr["header_field"].ToString();
                    else
                        caption = dr["header_field"].ToString().Substring(dr["header_field"].ToString().IndexOf("].[") + 3).TrimEnd(']');
                }
                xWriter.WriteString(caption);
                caption = "";

                xWriter.WriteEndElement();//Text
                xWriter.WriteStartElement("Left");
                xWriter.WriteString(left.ToString());
                xWriter.WriteEndElement();//Left
                xWriter.WriteStartElement("Calculated");
                xWriter.WriteString("true");
                xWriter.WriteEndElement();//Calculated
                xWriter.WriteStartElement("Width");
                xWriter.WriteString("1000");
                xWriter.WriteEndElement();//Width
                xWriter.WriteStartElement("Height");
                xWriter.WriteString("300");
                xWriter.WriteEndElement();//Height
                //Font
                xWriter.WriteStartElement("Font");
                xWriter.WriteStartElement("Bold");
                xWriter.WriteString("false");
                xWriter.WriteEndElement();//Bold
                xWriter.WriteStartElement("Name");
                xWriter.WriteString("Arial");
                xWriter.WriteEndElement();//Name
                xWriter.WriteStartElement("Size");
                xWriter.WriteString("8");
                xWriter.WriteEndElement();//Size
                xWriter.WriteEndElement();//Font
                xWriter.WriteEndElement();//Field  

                left += 1200;
                idx++;
            }
            dtG = null;
            #endregion

            #region Report Grouping Subtotal
            left = 50;
            //Header
            dtS = dsR.Tables["p_report_grouping_subtotal"];
            if (dtS == null)
                dtS = new DataTable();
            foreach (DataRow dr in dtS.Rows)
            {
                //Header Label
                xWriter.WriteStartElement("Field");
                xWriter.WriteStartElement("Name");
                xWriter.WriteString("Field" + idx.ToString());
                xWriter.WriteEndElement();//Name
                xWriter.WriteStartElement("Section");
                if (dr["group_sequence"].ToString() == "1")
                    xWriter.WriteString("6");
                else if (dr["group_sequence"].ToString() == "2")
                    xWriter.WriteString("8");
                else if (dr["group_sequence"].ToString() == "3")
                    xWriter.WriteString("10");
                xWriter.WriteEndElement();//Section
                xWriter.WriteStartElement("Text");
                string formula = "";
                if (lblReportSrc.Text.ToLower() == "object")
                    formula = "Format(Sum([" + setCaption(lblReportSrc.Text, dr["subtotal_field"].ToString(), "") + "])," + "\"0.00\")";
                else if (lblReportSrc.Text.ToLower() == "sql")
                {
                    if (dr["subtotal_field"].ToString().IndexOf("].[") == -1)
                        formula = "Format(Sum(" + dr["subtotal_field"].ToString() + ")," + "\"0.00\")";
                    else
                        formula = "Format(Sum(" + dr["subtotal_field"].ToString().Substring(dr["subtotal_field"].ToString().IndexOf("].[") + 3).TrimEnd(']') + ")," + "\"0.00\")";
                }
                xWriter.WriteString(formula);
                formula = "";

                xWriter.WriteEndElement();//Text
                xWriter.WriteStartElement("Left");
                xWriter.WriteString(hsRptLocations[dr["subtotal_field"].ToString()].ToString());
                xWriter.WriteEndElement();//Left
                xWriter.WriteStartElement("Calculated");
                xWriter.WriteString("true");
                xWriter.WriteEndElement();//Calculated
                xWriter.WriteStartElement("Width");
                xWriter.WriteString("1000");
                xWriter.WriteEndElement();//Width
                xWriter.WriteStartElement("Height");
                xWriter.WriteString("300");
                xWriter.WriteEndElement();//Height
                //Font
                xWriter.WriteStartElement("Font");
                xWriter.WriteStartElement("Bold");
                xWriter.WriteString("true");
                xWriter.WriteEndElement();//Bold
                xWriter.WriteStartElement("Name");
                xWriter.WriteString("Arial");
                xWriter.WriteEndElement();//Name
                xWriter.WriteStartElement("Size");
                xWriter.WriteString("8");
                xWriter.WriteEndElement();//Size
                xWriter.WriteEndElement();//Font
                xWriter.WriteEndElement();//Field   
                idx++;
            }
            dtS = null;
            #endregion

            #region Report Grand Total
            left = 50;
            //Header
            dtG = dsR.Tables["p_report_grouping_grand_total"];
            if (dtG == null)
                dtG = new DataTable();
            foreach (DataRow dr in dtG.Rows)
            {
                //Header Label
                xWriter.WriteStartElement("Field");
                xWriter.WriteStartElement("Name");
                xWriter.WriteString("Field" + idx.ToString());
                xWriter.WriteEndElement();//Name
                xWriter.WriteStartElement("Section");
                xWriter.WriteString("2");
                xWriter.WriteEndElement();//Section
                xWriter.WriteStartElement("Text");
                string formula = "";
                if (lblReportSrc.Text.ToLower() == "object")
                    formula = "Format(Sum([" + setCaption(lblReportSrc.Text, dr["grand_total_field"].ToString(), "") + "])," + "\"0.00\")";
                else if (lblReportSrc.Text.ToLower() == "sql")
                {
                    if (dr["grand_total_field"].ToString().IndexOf("].[") == -1)
                        formula = "Format(Sum(" + dr["grand_total_field"].ToString() + ")," + "\"0.00\")";
                    else
                        formula = "Format(Sum(" + dr["grand_total_field"].ToString().Substring(dr["grand_total_field"].ToString().IndexOf("].[") + 3).TrimEnd(']') + ")," + "\"0.00\")";
                }
                xWriter.WriteString(formula);
                formula = "";

                xWriter.WriteEndElement();//Text
                xWriter.WriteStartElement("Left");
                xWriter.WriteString(hsRptLocations[dr["grand_total_field"].ToString()].ToString());
                xWriter.WriteEndElement();//Left
                xWriter.WriteStartElement("Calculated");
                xWriter.WriteString("true");
                xWriter.WriteEndElement();//Calculated
                xWriter.WriteStartElement("Width");
                xWriter.WriteString("1000");
                xWriter.WriteEndElement();//Width
                xWriter.WriteStartElement("Height");
                xWriter.WriteString("300");
                xWriter.WriteEndElement();//Height
                //Font
                xWriter.WriteStartElement("Font");
                xWriter.WriteStartElement("Bold");
                xWriter.WriteString("true");
                xWriter.WriteEndElement();//Bold
                xWriter.WriteStartElement("Name");
                xWriter.WriteString("Arial");
                xWriter.WriteEndElement();//Name
                xWriter.WriteStartElement("Size");
                xWriter.WriteString("8");
                xWriter.WriteEndElement();//Size
                xWriter.WriteEndElement();//Font
                xWriter.WriteEndElement();//Field   
                idx++;
            }
            dtG = null;
            #endregion

            #region Footer Text
            if (txtFooterText.Text.Trim() != "")
            {
                xWriter.WriteStartElement("Field");
                xWriter.WriteStartElement("Name");
                xWriter.WriteString("lblFooField");
                xWriter.WriteEndElement();//Name
                xWriter.WriteStartElement("Section");
                xWriter.WriteString("2");
                xWriter.WriteEndElement();//Section
                xWriter.WriteStartElement("Text");
                xWriter.WriteString(txtFooterText.Text);
                xWriter.WriteEndElement();//Text
                xWriter.WriteStartElement("Width");
                xWriter.WriteString("5000");
                xWriter.WriteEndElement();//Width
                xWriter.WriteStartElement("Height");
                xWriter.WriteString("300");
                xWriter.WriteEndElement();//Height
                xWriter.WriteStartElement("Left");
                xWriter.WriteString("15");
                xWriter.WriteEndElement();//Height
                xWriter.WriteEndElement();//Field
            }
            #endregion

            #region Display Date
            if (chkDisplayDate.Checked == true)
            {
                xWriter.WriteStartElement("Field");
                xWriter.WriteStartElement("Name");
                xWriter.WriteString("lblDateField");
                xWriter.WriteEndElement();//Name
                xWriter.WriteStartElement("Section");
                xWriter.WriteString("4");
                xWriter.WriteEndElement();//Section
                xWriter.WriteStartElement("Text");
                xWriter.WriteString(DateTime.Now.ToShortDateString());
                xWriter.WriteEndElement();//Text
                xWriter.WriteStartElement("Width");
                xWriter.WriteString("5000");
                xWriter.WriteEndElement();//Width
                xWriter.WriteStartElement("Height");
                xWriter.WriteString("300");
                xWriter.WriteEndElement();//Height
                xWriter.WriteEndElement();//Field
            }
            #endregion

            #region Display Page Number
            if (chkDisplayPageNum.Checked == true)
            {
                xWriter.WriteStartElement("Field");
                xWriter.WriteStartElement("Name");
                xWriter.WriteString("lblPageField");
                xWriter.WriteEndElement();//Name
                xWriter.WriteStartElement("Section");
                xWriter.WriteString("4");
                xWriter.WriteEndElement();//Section
                xWriter.WriteStartElement("Text");
                xWriter.WriteString("Page No");
                xWriter.WriteEndElement();//Text
                xWriter.WriteStartElement("Width");
                xWriter.WriteString("2000");
                xWriter.WriteEndElement();//Width
                xWriter.WriteStartElement("Height");
                xWriter.WriteString("300");
                xWriter.WriteEndElement();//Height
                xWriter.WriteStartElement("Left");
                xWriter.WriteString("9000");
                xWriter.WriteEndElement();//Left
                xWriter.WriteEndElement();//Field

                xWriter.WriteStartElement("Field");
                xWriter.WriteStartElement("Name");
                xWriter.WriteString("lblPageNum");
                xWriter.WriteEndElement();//Name
                xWriter.WriteStartElement("Section");
                xWriter.WriteString("4");
                xWriter.WriteEndElement();//Section
                xWriter.WriteStartElement("Text");
                xWriter.WriteString("[Page]");
                
                xWriter.WriteEndElement();//Text
                xWriter.WriteStartElement("Width");
                xWriter.WriteString("300");
                xWriter.WriteEndElement();//Width
                xWriter.WriteStartElement("Height");
                xWriter.WriteString("300");
                xWriter.WriteEndElement();//Height
                xWriter.WriteStartElement("Left");
                xWriter.WriteString("11500");
                xWriter.WriteEndElement();//Left
                xWriter.WriteStartElement("Calculated");
                xWriter.WriteString("true");
                xWriter.WriteEndElement();//Calculated
                xWriter.WriteEndElement();//Field
            }
            #endregion

            hsRptLocations = null;
            xWriter.WriteEndElement();//Fields
            xWriter.WriteEndElement();//Report
            xWriter.WriteEndElement();//Reports
            xWriter.WriteEndDocument();
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("generateReportXML : Error : " + ex.Message);
            isGenerated = false;
        }
        finally
        {
            if (xWriter != null)
            {
                xWriter.Flush();
                xWriter.Close();
                xWriter = null;
            }
        }
        return isGenerated;
    }

    private string getOwnerName(string attrib_id, string objName)
    {
        string resultQry = attrib_id;
        try
        {
            string userDisplayField = hdd.GetColumnValue("sy_acr_mem", "mem_id", "af_row_id='30583eb791cb7d5b'");
            userDisplayField = userDisplayField.Trim().Length == 0 ? "user_id" : userDisplayField;

            DataTable dt = hdd.GetDataTable("select object_table from sy_obj where [object_id]='" + objName + "'");
            if (dt.Rows.Count > 0)
                resultQry = "select top 1 " + userDisplayField + " from sy_usr where af_row_id=" + dt.Rows[0]["object_table"].ToString() + "." + attrib_id;
            else
                resultQry = "select top 1 " + userDisplayField + " from sy_usr where af_row_id=" + objName + "." + attrib_id;
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("getOwnerName : Error : " + ex.Message);
        }
        return resultQry;
    }
    /*
    void reportViewer_PrintSection(object sender, C1.C1Report.ReportEventArgs e)
    {
        
        //bool _toggle = false;
        //Section sec = reportViewer.Report.Sections[e.Section];
        //switch (e.Section)
        //{
        //    case SectionTypeEnum.Detail:                
        //        sec.BackColor = (_toggle) ? System.Drawing.Color.Aqua : System.Drawing.Color.White;
        //        _toggle = !_toggle;
        //        break;
        //    default:
        //        break;
        //    //case SectionTypeEnum.Header:
        //    //    sec.BackColor = System.Drawing.Color.AliceBlue;
        //    //    break;
        //    //case SectionTypeEnum.PageHeader:
        //    //    sec.BackColor = System.Drawing.Color.ForestGreen;
        //    //    break;
        //    //case SectionTypeEnum.PageFooter:
        //    //    sec.BackColor = System.Drawing.Color.Olive;
        //    //    break;
        //    //case SectionTypeEnum.Footer:
        //    //    sec.BackColor = System.Drawing.Color.Orange;
        //    //    break;
        //    //case SectionTypeEnum.GroupHeader1:
        //    //    sec.BackColor = System.Drawing.Color.AliceBlue;
        //    //    break;
        //    //case SectionTypeEnum.GroupFooter1:
        //    //    sec.BackColor = System.Drawing.Color.AliceBlue;
        //    //    break;
        //    //case SectionTypeEnum.GroupHeader2:
        //    //    sec.BackColor = System.Drawing.Color.AliceBlue;
        //    //    break;
        //    //case SectionTypeEnum.GroupFooter2:
        //    //    sec.BackColor = System.Drawing.Color.AliceBlue;
        //    //    break;
        //    //case SectionTypeEnum.GroupHeader3:
        //    //    sec.BackColor = System.Drawing.Color.AliceBlue;
        //    //    break;
        //    //case SectionTypeEnum.GroupFooter3:
        //    //    sec.BackColor = System.Drawing.Color.AliceBlue;
        //    //    break;
        //    //case SectionTypeEnum.GroupHeader4:
        //    //    sec.BackColor = System.Drawing.Color.AliceBlue;
        //    //    break;
        //    //case SectionTypeEnum.GroupFooter4:
        //    //    sec.BackColor = System.Drawing.Color.AliceBlue;
        //    //    break;
        //}
    }
    */
    private void getpageicons() // added by srivatsan to get page icons
    {
        PageIcons icons = new PageIcons();
        HDDatabase HDD = new HDDatabase();
        try
        {
            //wz_Report.HeaderText = "&nbsp;" + icons.geticontextfrompageset(Request.QueryString["pgs_id"].ToString(), 2) + "&nbsp;" + wz_Report.HeaderText;
            Label lblcontrol = (Label)this.Master.FindControl("ctl00$ContentPlaceHolder3$wz_Report$HeaderContainer$Label3");
            lblcontrol.Text = "&nbsp;" + icons.geticontextfrompageset(Request.QueryString["pgs_id"].ToString(), 2) + "&nbsp;" + lblcontrol.Text;
          
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error :getpageicons() " + ex.Message);
           //wz_Report.HeaderText = "&nbsp;<img src =Images/MBIcons/small/default.gif><img>&nbsp;"+ wz_Report.HeaderText;

        }
        finally
        {
            icons = null;
            HDD = null;
        }
    }

    private void loadOwneridDropDown() // Added by srivatsan for owner id change
    {
        HDDatabase Hdd = new HDDatabase();
        BindControl BC = new BindControl();
        //DataSet ds = new DataSet();
        DataTable dt = null;
        try
        {
            //string bindid = Hdd.GetColumnValue("select mem_value3 from sy_acr_mem where acr_id = 'cee69885ce44589c' and mem_id = 'owner_id'");
            //BC.Bind(bindid, ddownerid, ref dt);

            //if (Session["user_afrowid"].ToString() == "e51e0327224a2eb9")
           // {
                //ddownerid.Items.Add(new ListItem(Session["userid"].ToString(), Session["user_afrowid"].ToString()));
           // }

            if (Request.QueryString["PK"] == null)
            {
                //ddownerid.SelectedValue = Session["user_afrowid"].ToString();
                owner_id.Value = Session["user_afrowid"].ToString();
                txt_owner_id.Text = Session["userid"].ToString();
            }
            if (Request.QueryString["PK"] != null)
            {
                if (Request.QueryString["CPY"] != null)
                {
                    //ddownerid.SelectedValue = Session["user_afrowid"].ToString();
                    owner_id.Value = Session["user_afrowid"].ToString();
                    txt_owner_id.Text = Session["userid"].ToString();
                }

            }

        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : loadOwneridDropDown :" + ex.Message);
        }
        finally
        {
            Hdd = null;
            BC = null;
            dt = null;
        }
    }
    
    private bool validateOwnerid()
    {
        bool status = false;
        HDDatabase HDD = new HDDatabase();
        BindControl BC = new BindControl();
        
        DataSet dsBind = new DataSet();
        string sql = BC.GetBindSql("f496930dfe0b690f");
        dsBind = HDD.GetDataset(sql);
                           if (dsBind != null)
                            {
                                if (dsBind.Tables.Count > 0)
                                {
                                    if (dsBind.Tables[0].Rows.Count > 0)
                                    {
                                        DataRow[] drrbind = dsBind.Tables[0].Select("fld = '" + txt_owner_id.Text.Trim().Replace("'", "''") + "'");
                                        if (txt_owner_id.Text.Trim() != "")
                                        {
                                            if (drrbind.Length > 0)
                                            {
                                                owner_id.Value = drrbind[0]["val"].ToString();
                                                status = true;
                                            }
                                        }
                                        else
                                        {
                                            status = true;
                                            owner_id.Value = "";
                                        }
                                    }
                                    else
                                    {
                                        status = true;
                                        owner_id.Value = "";
                                    }
                                }
                            }
                            if (status != true)
                            {
                                lblMessage.Text = "&nbsp;<img src='Images/Error.gif' border='0'>&nbsp;Invalid data for Owner :" + txt_owner_id.Text;
                                //lblmessage2.Text = "&nbsp;<img src='Images/Error.gif' border='0'>&nbsp;Invalid data for Owner :" + txt_owner_id.Text;
                                lblGroupMsg.Text = "&nbsp;<img src='Images/Error.gif' border='0'>&nbsp;Invalid data for Owner :" + txt_owner_id.Text;
                            }
                            return status;                                                
                                            
    }

    private string getUseraf_row_idfromUser(string userid)
    {
        string result = "";
        try
        {
            string sql = "select af_row_id from sy_usr where user_id = '"+userid+"'";
            result = hdd.GetColumnValue(sql);
        }
        catch
        {

        }

        return result;

    }

    private string getWhereCondition()
    {
        string sAFAdmin = "";
        try
        {
            SecurityFilter objSec = new SecurityFilter();
            sAFAdmin = objSec.QueryForAFAdmin();
            string sCustodianFilter = objSec.QueryForCustodianFilter();
            if (sCustodianFilter.Trim() != "")
                if (!sCustodianFilter.StartsWith("or"))
                {
                    if (sAFAdmin.Trim() != "")
                        sAFAdmin = "(" + sAFAdmin + " and " + sCustodianFilter + ") ";
                    else
                        sAFAdmin = "(" + sCustodianFilter + ") ";
                }
                else
                {
                    if (sAFAdmin.Trim() != "")
                        sAFAdmin = "(" + sAFAdmin + " " + sCustodianFilter + ") ";
                    else
                        sAFAdmin = "(" + sCustodianFilter + ") ";
                }
            objSec = null;
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("getWhereCondition : Error : " + ex.Message);
        }
        return sAFAdmin;
    }

    private string applysecurity(string sql)
    {
        try
        {
            SecurityFilter objSec = new SecurityFilter();
            string sAFAdmin = objSec.QueryForAFAdmin();
            string sCustodianFilter = objSec.QueryForCustodianFilter();
            if (sCustodianFilter.Trim() != "")
            if (!sCustodianFilter.StartsWith("or"))
                sAFAdmin += " and " + sCustodianFilter;
            else
                sAFAdmin = "(" + sAFAdmin + " " + sCustodianFilter + ") ";

            if (sql.Contains("order by"))
            {
                if (sAFAdmin.Trim() != "")
                    sql = sql.Replace("order by", "where " + sAFAdmin + " or object_id in (select object_id from sy_report_obj where rpt_id in (select report_id from sy_report_acc where role_id = '" + HttpContext.Current.Session["roleid"] + "' and is_accessible = 1)) order by");
            }
            else
            {
                if (sAFAdmin.Trim() != "")
                    sql = sql + " where " + sAFAdmin + " or object_id in (select object_id from sy_report_obj where rpt_id in (select report_id from sy_report_acc where role_id = '" + HttpContext.Current.Session["roleid"] + "' and is_accessible = 1))";
            }
        }
        catch
        {

        }
        return sql;
    }

    private void CheckForChangeOwner()  // Added by srivatsan to Check if user can change owner
    {
        try
        {
            security sec = new security();
            bool status = false;
            status = sec.getRightsForMRUObjects(HttpContext.Current.Request.QueryString["pgs_id"].ToString(), "change_owner");
            if (status == false)
            {

             txt_owner_id.Enabled = false;
                imgsearch.Visible= false;
            }

            sec = null;
        }
        catch
        {

        }
    }

    protected void StartNextButton_Click(object sender, EventArgs e)
    {        
    }

    protected void btnReport_Click(object sender, EventArgs e)
    {
        //showing the save report form
        
    }

    protected void btnAddGrouping_click(object sender, EventArgs e)
    {
        //hiddenGroupCnt.Value = Session["groupCount"].ToString();
        if (Convert.ToInt32(hiddenGroupCnt.Value) + 1 <= 3)
        {
            hiddenGroupCnt.Value = Convert.ToString((Convert.ToInt32(hiddenGroupCnt.Value) + 1));
            createGroupingForm(Convert.ToInt32(hiddenGroupCnt.Value));
            //Session["groupCount"] = hiddenGroupCnt.Value;
            collect_step_values(2);
            if (Convert.ToInt32(hiddenGroupCnt.Value) == 3)
            {
                lblAddGrouping.ForeColor = System.Drawing.Color.LightGray;
                btnAddGrouping.Enabled = false;
            }
        }
    }

    protected void btnSaveRep_start_Click(object sender, ImageClickEventArgs e)
    {
        collect_step_values(wz_Report.ActiveStepIndex);
        if (SaveData())
        {
            lblMessage.Text = "Data inserted successfully";
            EventArgs ee = new EventArgs();
            wz_Report_CancelButtonClick(sender, ee);
        }
    }

    protected void btnSaveRep_step_Click(object sender, ImageClickEventArgs e)
    {
        collect_step_values(wz_Report.ActiveStepIndex);
        if (SaveData())
        {
            lblMessage.Text = "Data inserted successfully";
            EventArgs ee = new EventArgs();
            wz_Report_CancelButtonClick(sender, ee);
        }
    }

    [System.Web.Services.WebMethodAttribute(), System.Web.Script.Services.ScriptMethodAttribute()]
    public static string GetDynamicContent(string contextKey)
    {
        return default(string);
    }

    private bool validateFields()
    {
        try
        {
            if (cmbObjects.SelectedValue == "")
            {
                lblFieldsMsg1.Text = "Please select a table/query from the list";
                return false;
            }
            else if (lstSelectedFields1.Items.Count == 0)
            {
                lblFieldsMsg1.Text = "Please select one or more fields from the list";
                return false;
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("validateFields : Error : " + ex.Message);
        }
        return true;
    }

    protected void mnuOptions_MenuItemClick(object sender, MenuEventArgs e)
    {
        try
        {
            if (!validateFields()) return;

            collect_step_values(wz_Report.ActiveStepIndex);
            if (e.Item.Text != "Save As")
            {
                if (!SaveData())
                    return;
            }
            switch (e.Item.Text)
            {
                case "Save":
                    wz_Report_CancelButtonClick(sender, e);
                    break;
                case "Save As":
                    IsEdit = false;
                    hiddenTmp.Value = "SaveAs";
                    if (!SaveData())
                        return;
                    wz_Report_CancelButtonClick(sender, e);
                    break;
                case "Save & Preview":
                    wz_Report.ActiveStepIndex = 6; 
                    generateReport(false, "");
                    break;
                case "Save & Print":
                    wz_Report_CancelButtonClick(sender, e);
                    break;
                case "Save & Export":
                    wz_Report.ActiveStepIndex = 6; 
                    generateReport(true, "XLS");
                    break;
                case "Save & Email":
                    wz_Report.ActiveStepIndex = 6; 
                    generateReport(false, "");
                    //if (generateReport()) // (generateReportXML(dsReport))
                    //{
                    //    //if (File.Exists(Server.MapPath(".") + "\\report\\" + hf_af_row_id1.Value + ".xml"))
                    //    //{
                    //    //    reportViewer.Report.Load(Server.MapPath(".") + "\\report\\" + hf_af_row_id1.Value + ".xml", txtRepName.Text);

                    //        //string fileName = Server.MapPath(".") + "\\report\\" + hf_af_row_id1.Value + ".pdf";
                    //        //reportViewer.Report.RenderToFile(fileName, C1.C1Report.FileFormatEnum.PDF);

                    //        //CommonFunctions cf = new CommonFunctions();
                    //        //FileStream fs = new FileStream(fileName, FileMode.Open);
                    //        //byte[] content = new byte[fs.Length];
                    //        //fs.Read(content, 0, content.Length);
                    //        //string ss = cf.sendEmail("sampathkumar_muruganandam@cellarstone.com", "sampathkumar_muruganandam@cellarstone.com", true, "Test Report", "Report attached", content, fileName);
                    //        //if (ss.ToLower() != "success")
                    //        //    LogWriter.WriteLog("Save & Mail : Error : Unable to send email");                            
                    //    //}
                    //    //else
                    //    //    LogWriter.WriteLog("mnuOptions_MenuItemClick-Save-Email: Error: Report file is not found");
                    //}                    
                    wz_Report_CancelButtonClick(sender, e);
                    break;
                case "Save & Close":
                    wz_Report_CancelButtonClick(sender, e);
                    break;
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("mnuOptions_MenuItemClick : Error : " + ex.Message);
        }
    }

    protected void btnPreview_Click(object sender, EventArgs e)
    {
        try
        {
            //if (wz_Report.ActiveStepIndex == 1)
            //{
            //    if (!validateCaptions())
            //    {
            //        wz_Report.ActiveStepIndex = 1;
            //        lblMessage.Text = "Captions are same. Please modify the captions";
            //        return;
            //    }
            //}
            collect_step_values(wz_Report.ActiveStepIndex);
            wz_Report.ActiveStepIndex = 6; 
            generateReport(false, "");
            //if (generateReportXML(dsReport))
            //{
            //    //if (File.Exists(Server.MapPath(".") + "\\report\\" + hf_af_row_id1.Value + ".xml"))
            //    //{
            //    //    wz_Report.ActiveStepIndex = 5;
            //    //    if (txtRepName.Text.Trim() == "")
            //    //        reportViewer.Report.Load(Server.MapPath(".") + "\\report\\" + hf_af_row_id1.Value + ".xml", "New Report");
            //    //    else
            //    //        reportViewer.Report.Load(Server.MapPath(".") + "\\report\\" + hf_af_row_id1.Value + ".xml", txtRepName.Text);
            //    //}
            //    //else
            //    //    LogWriter.WriteLog("btnPreview_Click: Error: Report file is not found");
            //}
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("btnPreview_Click : Error : " + ex.Message);
        }
    }

    protected void lnkExport_Click(object sender, EventArgs e)
    {
        try
        {
            wz_Report.ActiveStepIndex = 6; 
            generateReport(true, ddlExport.SelectedItem.Value);
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("lnkExport_Click : Error: " + ex.Message);
        }
    }

    private void IsActionMode()
    {

        try
        {
            if (Request.QueryString["action"] != null)
            {
                if (Request.QueryString["action"].ToString() == "1")
                {
                    NameValueCollection querystring = HttpUtility.ParseQueryString(Request.UrlReferrer.Query);
                    string strPagesetRowId = querystring["pgs_id"];
                    string strMenuRowId = querystring["mn"];
                    string strPK = Request.QueryString["ID"].ToString();
                    string temp = querystring["test"];
                    if (Request.QueryString["Vmode"] != null)
                    {
                        string redirect = "ReportWizard_New.aspx?pgs_id=6421de320e189de8&mn=613e91a1131935a0&PK=" + strPK + "&vmode=1";
                        Response.Redirect(redirect);
                    }
                    else if (Request.QueryString["PK"] == null)
                    {
                        Response.Redirect("ReportWizard_New.aspx?mn=613e91a1131935a0&pgs_id=6421de320e189de8");
                    }
                }
            }

        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("IsActionMode : Error: " + ex.Message);
        }
    }

    protected void mnuExportoptions_MenuItemClick(object sender, MenuEventArgs e)
    {
        try
        {
            if (!validateFields()) return;

            collect_step_values(wz_Report.ActiveStepIndex);
            wz_Report.ActiveStepIndex = 6; 
            generateReport(true, e.Item.Value);
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("mnuExportoptions_MenuItemClick : Error: " + ex.Message);
        }
    }

    protected void btnExport_Click(object sender, ImageClickEventArgs e)
    {
        try
        {
            collect_step_values(wz_Report.ActiveStepIndex);
            wz_Report.ActiveStepIndex = 6; 
            generateReport(true, "XLS");
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("btnExport_Click : Error : " + ex.Message);
        }        
    }
    /// <summary>
    /// This will add default Objects from sy_acr_mem to DataTable
    /// </summary>
    /// <param name="dtInput">DataTable of objects</param>
    private void AddDefaultObjects(ref DataTable dtInput) // Added by srivatsan for Default Objects Load
    {
        HDDatabase HDD = new HDDatabase();
        try
        {
            string objectids = "";
            if (dtInput != null)
            {
                foreach (DataRow dr in dtInput.Rows)
                {
                    objectids += "'" + dr["object_id"].ToString() + "',";
                }
                if (objectids.EndsWith(","))
                    objectids = objectids.TrimEnd(',');
            }
            string strSQL = "select mem_id,mem_name from sy_acr_mem where acr_id = '1b8bcdd101823723' and mem_value1 = 'true' order by mem_name";
            if (objectids.Trim() != "")
                strSQL = "select mem_id,mem_name from sy_acr_mem where acr_id = '1b8bcdd101823723' and mem_value1 = 'true' and mem_value1 not in (" + objectids + ") order by mem_name";
            DataTable dt = HDD.GetDataTable(strSQL);

            if (dt != null)
                if (dt.Rows.Count > 0)
                    foreach (DataRow dr in dt.Rows)
                    {
                        DataRow drInput = dtInput.NewRow();
                        drInput["object_name"] = dr["mem_name"].ToString();
                        drInput["object_id"] = dr["mem_id"].ToString();
                        dtInput.Rows.Add(drInput);
                    }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : AddDefaultObjects : " + ex.Message);
        }
        finally
        {
            HDD = null;
        }
    }

    private string wrapItAsMessage(string msg, bool isError)
    {
        return "<div class=\"" + (isError == true ? "mbErrorMessage" : "mbMessage") + "\">" + msg + "</div>";
    }

    /// <summary>
    /// To fill the step 3 wizard fields for source filter.
    /// </summary>
    private void FillSourceFilterFields() // Added by Imran Gani on 20-Jul-2012, for Source Filter.
    {
        string sObject_id = string.Empty;
        try
        {
            if (cmbObjects.SelectedIndex == -1) return;

            if (cmbObjects.SelectedValue.Trim() == "")
            {
                cmdColumn_Name.Items.Clear();
                //cmbValue.Items.Clear();
                txtValue.Text = ""; // Added by Imran Gani on 25-Sep-2012, for autocomplete.
                cmbCondition.Items.Clear();
                return;
            }
            lblSrcFilMsg.Text = "";
            if (cmbObjects.SelectedValue.ToUpper().StartsWith("OBJECT@"))
            {
                string sql = "SELECT * from sy_pg_ctr where page_id = (SELECT af_row_id from sy_pg where object_id = '" + cmbObjects.SelectedValue.ToString().Substring(cmbObjects.SelectedValue.IndexOf("@") + 1) + "');select * from sy_acr_mem where acr_id='3123fa00e7b08e2B';";
                dsRptSrcFlt = hdd.GetDataset(sql);
                //cmbValue.Items.Clear();
                txtValue.Text = ""; // Added by Imran Gani on 25-Sep-2012, for autocomplete.
                cmbCondition.Items.Clear();
                cmdColumn_Name.Items.Clear();
                cmdColumn_Name.Items.Add(new ListItem("--Select a field--", ""));
                foreach (DataRow dr in dsRptSrcFlt.Tables[0].Select("", "control_name asc"))
                {
                    string sField = dr["control_id"].ToString().ToLower();
                    if (sField != "created_by" && sField != "created_at" && sField != "modified_at" && sField != "modified_by" && sField != "owner_id" && sField != "af_row_id")
                    {
                        ListItem liObject = new ListItem(dr["control_name"].ToString(), dr["af_row_id"].ToString());
                        cmdColumn_Name.Items.Add(liObject);
                    }
                }
                foreach (DataRow dr in dsRptSrcFlt.Tables[1].Select("", "mem_seq asc"))
                {
                    ListItem liObject = new ListItem(dr["mem_name"].ToString(), dr["mem_id"].ToString());
                    cmbCondition.Items.Add(liObject);
                }
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : FillSourceFilterFields : " + ex.Message);
        }
        finally
        {
        }
    }

    /// <summary>
    /// To set the source filter details into DataTable of source filter.
    /// </summary>
    /// <param name="dt">DataTable of source filter.</param>
    private void getSourceFilter(DataTable dt) // Added by Imran Gani on 20-Jul-2012, for Source Filter.
    {
        //Localization ll = new Localization(); // Added by Imran Gani on 28-Sep-2012, to handle date/time field.  // Commented by 'Imran Gani' on 28-Feb-2014, for MBLocale
        DataTable dtfil = new DataTable();
        DataTable dtSrcfil = new DataTable();
        bool isDate = false;
        string sFldType = "";
        try
        {
            string strFilterTable = hfFilterTable.Value.ToString();
            strFilterTable = "{\"a\":[ " + strFilterTable + " ]}";
            dtfil = JsonFunctions.JsonFunctions.JsonToDataTable(strFilterTable);
            if (dt.Rows.Count > 0)
            {
                dtSrcfil = dt.Copy();
                dt.Clear();
                int i = 0;
                foreach (DataRow dr1 in dtfil.Rows)
                {
                    sFldType = dsRptSrcFlt.Tables[0].Select("af_row_id='" + dr1["fldid"].ToString().Replace("'", "''") + "'")[0]["control_attrib_type"].ToString();
                    if (sFldType == "DA" || sFldType == "DT")
                        isDate = true;
                    DataRow[] dr = dtSrcfil.Select("field='" + dr1["fldid"].ToString().Replace("'", "''") + "' and condition='" + dr1["cndid"].ToString() + "' and field_value='" + dr1["val"].ToString().Replace("'", "''") + "'");
                    if (dr.Length > 0)
                    {
                        DataRow drExist = dr[0];
                        i++;
                        drExist["sequence"] = i;
                        drExist["field"] = dr1["fldid"].ToString();
                        drExist["condition"] = dr1["cndid"].ToString();
                        //drExist["field_value"] = isDate == true ? ll.getInvariantDate(dr1["val"].ToString()) : dr1["val"].ToString();  // Commented by 'Imran Gani' on 28-Feb-2014, for MBLocale
                        drExist["field_value"] = isDate == true ? MBLocalization.getDateValue(HttpContext.Current.Session["userlocale"].ToString(), dr1["val"].ToString()) : dr1["val"].ToString();
                        dt.ImportRow(drExist);
                    }
                    else
                    {
                        DataRow drNew = dt.NewRow();
                        i++;
                        drNew["sequence"] = i;
                        drNew["field"] = dr1["fldid"].ToString();
                        drNew["condition"] = dr1["cndid"].ToString();
                        //drNew["field_value"] = isDate == true ? ll.getInvariantDate(dr1["val"].ToString()) : dr1["val"].ToString(); // Commented by 'Imran Gani' on 28-Feb-2014, for MBLocale
                        drNew["field_value"] = isDate == true ? MBLocalization.getDateValue(HttpContext.Current.Session["userlocale"].ToString(), dr1["val"].ToString()) : dr1["val"].ToString();
                        drNew["source_object"] = cmbObjects.SelectedValue.ToString().Substring(cmbObjects.SelectedValue.IndexOf("@") + 1);
                        dt.Rows.Add(drNew);
                    }
                }
            }
            else if (dtfil != null && dtfil.Rows.Count > 0)
            {
                int i = 0;
                foreach (DataRow dr1 in dtfil.Rows)
                {
                    sFldType = dsRptSrcFlt.Tables[0].Select("af_row_id='" + dr1["fldid"].ToString().Replace("'", "''") + "'")[0]["control_attrib_type"].ToString();
                    if (sFldType == "DA" || sFldType == "DT")
                        isDate = true;
                    DataRow dr = dt.NewRow();
                    i++;
                    dr["sequence"] = i;
                    dr["field"] = dr1["fldid"].ToString();
                    dr["condition"] = dr1["cndid"].ToString();
                    //dr["field_value"] = isDate == true ? ll.getInvariantDate(dr1["val"].ToString()) : dr1["val"].ToString(); // Commented by 'Imran Gani' on 28-Feb-2014, for MBLocale
                    dr["field_value"] = isDate == true ? MBLocalization.getDateValue(HttpContext.Current.Session["userlocale"].ToString(), dr1["val"].ToString()) : dr1["val"].ToString();
                    dr["source_object"] = cmbObjects.SelectedValue.ToString().Substring(cmbObjects.SelectedValue.IndexOf("@") + 1);
                    dt.Rows.Add(dr);
                }
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : getSourceFilter : " + ex.Message);
        }
        finally
        {
            dtSrcfil.Dispose(); dtfil.Dispose();
        }
    }

    /// <summary>
    /// To get the source filter display grid details.
    /// </summary>
    /// <param name="dt">DataTable of source filter.</param>
    /// <returns>Json String</returns>
    private string getSourceFilterInputData(DataTable dt) // Added by Imran Gani on 20-Jul-2012, for Source Filter.
    {
        security hdds = new security();
        BindControl bc = new BindControl();
        StringBuilder sbHidden = new StringBuilder();
        GenerateGrid gg = new GenerateGrid();
        ArrayList alValueList = new ArrayList();
        string sFld = string.Empty, sVal;
        try
        {
            foreach (DataRow dr in dt.Select("", "sequence"))
            {
                alValueList.Clear();
                sVal = dr["field_value"].ToString();
                if (sVal.Contains("|") && sVal.EndsWith("|"))
                {
                    sVal = sVal.TrimEnd('|');
                    alValueList.AddRange(sVal.Split('|'));
                }
                DataRow[] drPgCtr = dsRptSrcFlt.Tables[0].Select("af_row_id='" + dr["field"].ToString() + "'");
                if (drPgCtr.Length > 0)
                {
                    if (sVal != "" && drPgCtr[0]["control_bind_id"].ToString() != "")
                    {
                        string sBindSql = bc.GetBindSql_forValue(drPgCtr[0]["control_bind_id"].ToString());
                        if (alValueList.Count > 0)
                        {
                            sVal = "";
                            foreach (string sValue in alValueList)
                            {
                                sVal += hdd.GetColumnValue(sBindSql + "'" + sValue + "'") + ", ";
                            }
                            sVal = sVal.Trim();
                        }
                        else
                            sVal = hdd.GetColumnValue(sBindSql + "'" + sVal + "'");
                    }
                    if (drPgCtr[0]["control_attrib_type"].ToString() == "DA" || drPgCtr[0]["control_attrib_type"].ToString() == "DT")
                        sVal = gg.manageDateTimeValues(drPgCtr[0]["control_attrib_type"].ToString().ToLower(), sVal);
                    if (alValueList.Count > 0 && drPgCtr[0]["control_bind_id"].ToString() == "")
                    {
                        sVal = "";
                        foreach (string sValue in alValueList)
                        {
                            sVal += sValue + ", ";
                        }
                        sVal = sVal.Trim();
                    }
                    DataRow drCond = dsRptSrcFlt.Tables[1].Select("mem_id='" + dr["condition"].ToString() + "'")[0];
                    sbHidden.Append("{\"fld\":\"" + drPgCtr[0]["control_name"].ToString() + "\",\"fldid\":\"" + dr["field"].ToString() + "\",\"cnd\":\"" + drCond["mem_name"].ToString() + "\",\"cndid\":\"" + dr["condition"].ToString() + "\",\"txt\":\"" + hdds.encodeForJs(sVal) + "\",\"val\":\"" + hdds.encodeForJs(dr["field_value"].ToString()) + "\"},");
                }
                else
                    return "";
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : getSourceFilterInputData : " + ex.Message);
        }
        finally
        {
            bc = null; gg = null; sFld = string.Empty; sVal = string.Empty; alValueList = null;
        }
        return sbHidden.ToString().TrimEnd(',');
    }

    /// <summary>
    /// To get the where condition for the object.
    /// </summary>
    /// <param name="sTableName">Table Name of Object</param>
    /// <returns>Where condition for object.</returns>
    private string getWhereCondForObj(string sTableName) // Added by Imran Gani on 20-Jul-2012, for Source Filter.
    {
        string sWhere = string.Empty, temp;
        DataTable dtSrcfil = new DataTable();
        try
        {
            if (dsReport.Tables.Contains("p_report_source_filter") && dsReport.Tables["p_report_source_filter"].Rows.Count > 0)
            {
                string strFilterTable = getSourceFilterInputData(dsReport.Tables["p_report_source_filter"]);
                strFilterTable = "{\"a\":[ " + strFilterTable + " ]}";
                dtSrcfil = JsonFunctions.JsonFunctions.JsonToDataTable(strFilterTable);
                if (dtSrcfil != null && dtSrcfil.Rows.Count > 0)
                {
                    if (dtSrcfil.Rows.Count > 1)
                    {
                        sWhere = dsReport.Tables["p_sy_report"].Rows[0]["source_filter_grouping"].ToString();
                        sWhere = sWhere.ToLower().Replace("and", " and ").Replace("or", " or ");
                        for (int j = 1; j <= dtSrcfil.Rows.Count; j++)
                        {
                            sWhere = sWhere.Replace(Convert.ToString(j) + " ", "$" + Convert.ToString(j)).Replace(" " + Convert.ToString(j), "$" + Convert.ToString(j));
                        }
                        int i = 0;
                        foreach (DataRow dr in dtSrcfil.Rows)
                        {
                            i++;
                            temp = getCondition(dr["cndid"].ToString(), dr["fldid"].ToString(), dr["val"].ToString(), sTableName, dsRptSrcFlt);
                            sWhere = sWhere.Replace("$" + Convert.ToString(i), temp);
                        }
                    }
                    else
                    {
                        sWhere = getCondition(dtSrcfil.Rows[0]["cndid"].ToString(), dtSrcfil.Rows[0]["fldid"].ToString(), dtSrcfil.Rows[0]["val"].ToString(), sTableName, dsRptSrcFlt);
                    }
                }
                else
                    sWhere = "1=1";
            }
            else
                sWhere = "1=1";
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : getWhereCondForObj : " + ex.Message);
        }
        finally
        {
            temp = string.Empty; dtSrcfil.Dispose();
        }
        return " where " + sWhere + ";";
    }

    /// <summary>
    /// To get the condition.
    /// </summary>
    /// <param name="sCondId">Condition</param>
    /// <param name="sFldId">Field</param>
    /// <param name="sVal">Value</param>
    /// <param name="sTableName">Table</param>
    /// <returns>Condition</returns>
    private string getCondition(string sCondId, string sFldId, string sVal, string sTableName, DataSet dsRptSrcFlt)
    {
        string temp = "";
        ArrayList alValueList = new ArrayList();
        try
        {
            if (sVal.Contains("|") && sVal.EndsWith("|"))
            {
                sVal = sVal.TrimEnd('|');
                alValueList.AddRange(sVal.Split('|'));
            }
            DataRow drCond = dsRptSrcFlt.Tables[1].Select("mem_id='" + sCondId + "'")[0];
            DataRow drColId = dsRptSrcFlt.Tables[0].Select("af_row_id='" + sFldId + "'")[0];
            switch (sCondId)
            {
                case "NULL":
                case "NNULL":
                    temp = "[" + sTableName + "].[" + drColId["control_id"].ToString().Replace("'", "''") + "] " + drCond["mem_value1"].ToString();
                    break;
                case "NEQ":
                    if (alValueList.Count > 0)
                    {
                        foreach (string sValue in alValueList)
                        {
                            temp += "[" + sTableName + "].[" + drColId["control_id"].ToString().Replace("'", "''") + "] " + drCond["mem_value1"].ToString() + " '" + sValue.Replace("'", "''") + "' and ";
                        }
                        temp = temp.Substring(0, temp.Length - 4);
                        temp += "or [" + sTableName + "].[" + drColId["control_id"].ToString().Replace("'", "''") + "] is null";
                    }
                    else
                        temp = "[" + sTableName + "].[" + drColId["control_id"].ToString().Replace("'", "''") + "] " + drCond["mem_value1"].ToString() + " '" + sVal.Replace("'", "''") + "' or [" + sTableName + "].[" + drColId["control_id"].ToString().Replace("'", "''") + "] is null";
                    break;
                case "IN":
                    if (alValueList.Count > 0)
                    {
                        foreach (string sValue in alValueList)
                        {
                            temp += "'" + sValue.Replace("'", "''") + "',";
                        }
                        temp = temp.TrimEnd(',');
                        temp = "[" + sTableName + "].[" + drColId["control_id"].ToString().Replace("'", "''") + "] " + drCond["mem_value1"].ToString() + " (" + temp + ")";
                    }
                    else
                        temp = "[" + sTableName + "].[" + drColId["control_id"].ToString().Replace("'", "''") + "] " + drCond["mem_value1"].ToString() + " '" + sVal.Replace("'", "''") + "'";
                    break;
                case "NIN":
                    if (alValueList.Count > 0)
                    {
                        foreach (string sValue in alValueList)
                        {
                            temp += "'" + sValue.Replace("'", "''") + "',";
                        }
                        temp = temp.TrimEnd(',');
                        temp = "[" + sTableName + "].[" + drColId["control_id"].ToString().Replace("'", "''") + "] " + drCond["mem_value1"].ToString() + " (" + temp + ")";
                    }
                    else
                        temp = "[" + sTableName + "].[" + drColId["control_id"].ToString().Replace("'", "''") + "] " + drCond["mem_value1"].ToString() + " '" + sVal.Replace("'", "''") + "'";
                    break;
                default:
                    if (alValueList.Count > 0)
                    {
                        foreach (string sValue in alValueList)
                        {
                            temp += "[" + sTableName + "].[" + drColId["control_id"].ToString().Replace("'", "''") + "] " + drCond["mem_value1"].ToString() + " '" + sValue.Replace("'", "''") + "' or ";
                        }
                        temp = temp.Substring(0, temp.Length - 4);
                    }
                    else
                        temp = "[" + sTableName + "].[" + drColId["control_id"].ToString().Replace("'", "''") + "] " + drCond["mem_value1"].ToString() + " '" + sVal.Replace("'", "''") + "'";
                    break;
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : getCondition : " + ex.Message);
        }
        finally
        {
            alValueList = null;
        }
        return temp;
    }
}
